- The document discusses file handling in Python, including opening, reading from, writing to, and closing text files.
- It describes opening files in different modes like reading, writing, and appending. It also shows how to read and write data from files line by line and how to process comma separated value (CSV) files.
- Examples are given of opening a file, reading its contents, splitting lines on commas, and writing data to files from arrays and records.
h2kinfosys is offering the IT Online Courses with Certificates ,H2kinfosys is the best place to learn online coding classes as we offer the most job oriented training led by experienced instructors through live classroom sessions. It courses online from h2kinfosys . top trending courses like learn tableau online, hadoop certification Training, python certification online and more courses register for free demo class .
https://www.h2kinfosys.com/
Outlines of this lecture:
- What is stream?
- File Output Stream Class
- File Input Stream Class
- Byte Array Output Stream Class
- Sequence Input Stream Class
- File Reader Class
- File Writer Class
- Scanner with String
h2kinfosys is offering the IT Online Courses with Certificates ,H2kinfosys is the best place to learn online coding classes as we offer the most job oriented training led by experienced instructors through live classroom sessions. It courses online from h2kinfosys . top trending courses like learn tableau online, hadoop certification Training, python certification online and more courses register for free demo class .
https://www.h2kinfosys.com/
Outlines of this lecture:
- What is stream?
- File Output Stream Class
- File Input Stream Class
- Byte Array Output Stream Class
- Sequence Input Stream Class
- File Reader Class
- File Writer Class
- Scanner with String
Docparser is a well-known third party application for document analysis.These blogs describe the docparser usage and its integration with Odoo using python api calls.
This is an intermediate conversion course for C++, suitable for second year computing students who may have learned Java or another language in first year.
This is ppt prsented by me in class in this ppt i include file handling in which i tell us about the types of files
creation of text file in C ++ ,updating a text file in C++ , printing the inforamtion in text file .creation of binary file in C ++ ,updating a binary file in C++ , printing the inforamtion in binary file, text file function and binary file function in c++ , File ponters ,syntax of every thing and use of file pointers and many more.
Docparser is a well-known third party application for document analysis.These blogs describe the docparser usage and its integration with Odoo using python api calls.
This is an intermediate conversion course for C++, suitable for second year computing students who may have learned Java or another language in first year.
This is ppt prsented by me in class in this ppt i include file handling in which i tell us about the types of files
creation of text file in C ++ ,updating a text file in C++ , printing the inforamtion in text file .creation of binary file in C ++ ,updating a binary file in C++ , printing the inforamtion in binary file, text file function and binary file function in c++ , File ponters ,syntax of every thing and use of file pointers and many more.
Python too supports file handling and allows users to handle files i.e., to read and write files, along with many other file handling options, to operate on files. The concept of file handling has stretched over various other languages, but the implementation is either complicated or lengthy, but alike other concepts of Python, this concept here is also easy and short. Python treats file differently as text or binary and this is important. Each line of code includes a sequence of characters and they form text file. Each line of a file is terminated with a special character, called the EOL or End of Line characters like comma {,} or newline character. It ends the current line and tells the interpreter a new one has begun. Let’s start with Reading and Writing files.
Instructions for Submissions thorugh G- Classroom.pptxJheel Barad
This presentation provides a briefing on how to upload submissions and documents in Google Classroom. It was prepared as part of an orientation for new Sainik School in-service teacher trainees. As a training officer, my goal is to ensure that you are comfortable and proficient with this essential tool for managing assignments and fostering student engagement.
This is a presentation by Dada Robert in a Your Skill Boost masterclass organised by the Excellence Foundation for South Sudan (EFSS) on Saturday, the 25th and Sunday, the 26th of May 2024.
He discussed the concept of quality improvement, emphasizing its applicability to various aspects of life, including personal, project, and program improvements. He defined quality as doing the right thing at the right time in the right way to achieve the best possible results and discussed the concept of the "gap" between what we know and what we do, and how this gap represents the areas we need to improve. He explained the scientific approach to quality improvement, which involves systematic performance analysis, testing and learning, and implementing change ideas. He also highlighted the importance of client focus and a team approach to quality improvement.
Operation “Blue Star” is the only event in the history of Independent India where the state went into war with its own people. Even after about 40 years it is not clear if it was culmination of states anger over people of the region, a political game of power or start of dictatorial chapter in the democratic setup.
The people of Punjab felt alienated from main stream due to denial of their just demands during a long democratic struggle since independence. As it happen all over the word, it led to militant struggle with great loss of lives of military, police and civilian personnel. Killing of Indira Gandhi and massacre of innocent Sikhs in Delhi and other India cities was also associated with this movement.
Unit 8 - Information and Communication Technology (Paper I).pdfThiyagu K
This slides describes the basic concepts of ICT, basics of Email, Emerging Technology and Digital Initiatives in Education. This presentations aligns with the UGC Paper I syllabus.
Synthetic Fiber Construction in lab .pptxPavel ( NSTU)
Synthetic fiber production is a fascinating and complex field that blends chemistry, engineering, and environmental science. By understanding these aspects, students can gain a comprehensive view of synthetic fiber production, its impact on society and the environment, and the potential for future innovations. Synthetic fibers play a crucial role in modern society, impacting various aspects of daily life, industry, and the environment. ynthetic fibers are integral to modern life, offering a range of benefits from cost-effectiveness and versatility to innovative applications and performance characteristics. While they pose environmental challenges, ongoing research and development aim to create more sustainable and eco-friendly alternatives. Understanding the importance of synthetic fibers helps in appreciating their role in the economy, industry, and daily life, while also emphasizing the need for sustainable practices and innovation.
Palestine last event orientationfvgnh .pptxRaedMohamed3
An EFL lesson about the current events in Palestine. It is intended to be for intermediate students who wish to increase their listening skills through a short lesson in power point.
The Art Pastor's Guide to Sabbath | Steve ThomasonSteve Thomason
What is the purpose of the Sabbath Law in the Torah. It is interesting to compare how the context of the law shifts from Exodus to Deuteronomy. Who gets to rest, and why?
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdfTechSoup
In this webinar you will learn how your organization can access TechSoup's wide variety of product discount and donation programs. From hardware to software, we'll give you a tour of the tools available to help your nonprofit with productivity, collaboration, financial management, donor tracking, security, and more.
2. Learning Intentions
By the end of this lesson learners will be able to:
❏ Open sequential text files
❏ Read from sequential text files
❏ Write to sequential text files
❏ Close text files
3. Saving data
You will have to save data at some point in your program.
There are various ways to do this:
❏ Files
❏ In the Registry
❏ In Databases
At Higher we will concentrate only on text/csv files.
There are various methods to access files in Python but we will be using the methods in
the File Object
4. Text File operations
Opening/Creating
When a text file is opened for access or a new empty file is created
Reading/Writing
When data is read from or written to a file
Closing
The file is closed and no further operations can take place
5. Opening Files
When a file is opened you have to specify how it should be opened
This is what type of access you will be using
When opening a file we can set the following modes
❏ Reading (default)
❏ Writing
❏ Appending
6. Some Python File Access Modes
Character Description
‘r’ Open for reading (default)
‘w’ Open for writing, truncating the file first
‘x’ Open for exclusive creation, failing if the file already
exists
‘a’ Open for writing, appending to the end of the file if it
exists
7. File Access Modes
Reading (r)
Opens the file if it exists and seeks to the end of the file, or creates a new file.
(default)
Writing (w)
Opens a file for writing, will create a new file if none exists
Reading and writing (r+)
Opens a file to read and write, will overwrite an existing file or create a new
one
Appending (a)
Opens an existing file to append, will append to the end of the file
8. File Reading Example Pseudocode
#-------------Main Program-----------------
OPEN FILE(SAMPLEFILE.txt) FOR READING
Filecontents = FILE.READ
CLOSE FILE
File exists in the
same folder as the
Python Program
9. File Reading Example Python
#-------------Main Program-----------------
with open("SampleFile.txt") as readfile:
filecontents = readfile.read()
print(filecontents)
File is automatically closed once the loop ends.
Remember to put Close File in exam situations
This would open the file for
reading
10. Different ways to read from a file
There are different ways to read the contents of a file
ReadLine
Reads a single line of characters from the file and returns the data as a string
Read
Reads all characters from the current position to the end of the stream
11. Different ways to write to a file
There are different ways to write to a file
Write - Writes a character to the stream
WriteLines(sequence) - Writes a sequence of strings to a file
12. Writing to a file example
#-------------Main Program-----------------
#open file
with open("newfile.txt","w") as writefile:
writefile.write("Python is great fun")
13. What about if you are reading a file like this
File Contents:
Joe,4
Joanna,40
Michael,50
etc..
This type of file can be known as a Comma Separated Values (CSV) file
It is just a plain text file where the text is delimited by a comma with each record usually
on a new line
Names and Ages
14. Processing comma separated files
Our file looks like:
Joe,80
Anna,83
We have to read and process the file in a particular manner
We will create two parallel arrays of 50 elements to store the names and
ages
We will need to process the file line by line
Then process the file using the comma as a separator
The different values are separated by a comma
Each record is on a different line
15. How to do this
1. We will create an two empty arrays of 50 elements
names[None] * 50
marks[None] * 50
1. While there is more text in the file we will read each line into a variable called line
2. Split the line where there is a comma using the split method
3. Each item will then be stored in a newly created array called items
4. Store the data into parallel arrays for names and marks
Items Array
Element Value
0 Joe
1 80name Array
Element Value
0 Joe
marks Array
Element Value
0 80
Joe,80
Anna,83
16. Example – Reading from a csv file
counter = 0
names = [None] * 50
marks = [None] * 50
with open("marks.txt") as readfile:
#read in a single line of the file and remove the end of line character
line = readfile.readline().rstrip('n')
#While there are more lines of text
while line:
items = line.split(",")
names[counter] = items[0]
Marks[counter] = items[1]
line = readfile.readline().rstrip('n')
counter += 1
split the line of text where there is a comma
each item will be stored in a separate element of
a list
the first element of the list will contain the name -
assign this to the names array
the second element of the list will contain
the mark, assign this to the names array
read in the next line of the file
17. Walk Through Step 1
Initialise the variable counter and the names and
marks arrays
Items Array
0
1
marks Array
0
name Array
0
line variable
counter
0
Joe,80
Anna,83
18. Walk Through Step 2
Open the File
Items Array
0
1
marks Array
0
name Array
0
line variable
counter
0
Joe,80
Anna,83
19. Walk Through Step 3
Read the first line of the file, stripping the new line character n
Items Array
0
1
marks Array
0
name Array
0
line variable
“Joe,80”
counter
0
Joe,80
Anna,83
20. Walk Through Step 4
While this line of text isn’t empty (there are some contents in the file)
Items Array
0
1
marks Array
0
name Array
0
line variable
“Joe,80”
counter
0
Joe,80
Anna,83
21. Walk Through Step 5
Split the text in the variable called line on any comma and store it the items array
Items Array
0 Joe
1 80
marks Array
0
name Array
0
line variable
“Joe,80”
counter
0
Joe,80
Anna,83
22. Walk Through Step 6
Place the first value in the Items array into the first value of the names array
Items Array
0 Joe
1 80
marks Array
0
name Array
0 Joe
line variable
“Joe,80”
counter
0
Joe,80
Anna,83
23. Walk Through Step 7
Place the second value in the Items array into the first value of the names array
Items Array
0 Joe
1 80
marks Array
0 80
name Array
0 Joe
line variable
“Joe,80”
counter
0
Joe,80
Anna,83
24. Walk Through Step 8
Read the second line of the file, stripping the new line character n
Items Array
0 Joe
1 83
marks Array
0 83
name Array
0 Joe
line variable
“Anna,83”
counter
0
Joe,80
Anna,83
25. Walk Through Step 9
Increment the counter variable so that new items will be placed at element 1 in the names and marks arrays
Items Array
0 Joe
1 83
marks Array
0 83
name Array
0 Joe
line variable
“Anna,83”
counter
1
Joe,80
Anna,83
26. Creating a csv File using variables
for counter in range(5):
name = input("Enter name: ")
age = input("Enter age: ")
with open("names.txt","w") as writefile:
writefile.write(name + ","+ str(age) + "n")
Writes that detail on one line
File mode set to writing
27. Creating a csv File from arrays
names = ["John","Anna","Mark","Michael"]
ages = [23,35,23,8]
with open("names.txt","w") as wfile:
for counter in range(len(names)):
wfile.write(names[counter] + ","+ str(ages[counter])+"n")
Puts an end of line character at
the end of the line
name Array
Element Value
0 John
1 Joan
ages Array
Element Value
0 23
1 35
John,23
Anna,35
28. Using records to write to files
For the next slide we will assume the following record structure shown below
And that we have an array of these member records called clubmembers which has 50
elements. A sample of the data is shown below to the right
Record Structure
RECORD member:
name :
STRING
age:
INTEGER
END RECORD
Record
Number
name age
0 John 23
1 Anna 35
29. Creating a csv File from records
with open("names.txt","w") as wfile:
for i in range(len(clubmembers)):
wfile.write(clubmembers[i].name + ","+ str(clubmembers[i].ages[i])+"n")
John,23
Anna,35
Record
Number
name age
0 John 23
1 Anna 35