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