Overview of the chapter:
- 13.9 Text files
13.9 Handling text files
Some data needs to be stored permanently. If stored in variables data will be lost when program stops / powered off. If stored in a file the data is no longer volatile.
You need to be able to perform the following tasks:
- Open the file, in read / write / append mode
- Operate the file, read / write
- Close the file
In the following languages:
13.9.1 Opening files
There are three methods of opening files: Read, Write, Append.
|Mode||Explanation||Pseudocode syntax||Python Syntax|
|Read||Open the file for reading its contents.||OPENFILE <filename> FOR READ||file = open(“<filename>”, “r”)|
|Write||Open the file for writing new contents. |
By writing all original data will be overridden.
|OPENFILE <filename> FOR WRITE||file = open(“<filename>”, “w”)|
|Append||Add more data to the end of the file.||OPENFILE <filename> FOR APPEND||file = open(“<filename>”, “a”)|
- In pseudocode there is no need to covert filename to string. But in python the filename must be in a string.
- In pseudocode the modes are key words, while in python the mode are strings.
It is not recommended to use the method of “WITH OPEN”. The method doesn’t need to close the file explicitly, but there is a mark given for the command. Teachers will often miss that mark if you use “WITH OPEN”.
13.9.2 File operations
|Read the next line from file||READFILE <filename>, <variableToAssign>||<variableToAssign> = file.readline()|
|Write a line to file||WRITEFILE <filename>, <stringValue>||file.write(<stringValue>)|
The READLINE command reads the next line of the file.
If the file is opened in “READ” mode, the WRITEFILE command will first erase everything in the file, then write the stringValue in.
If the file is opened in “APPEND” mode, the WRITEFILE command will only add the stringValue to the end.
13.9.3 Closing the file
Always close the file after editing. This command will update all the changes to the file.
|Close the file||CLOSEFILE <filename>||file.close()|
13.9.4 End-of-file marker
The marker is the only way to identify the whole file had been finished reading.
|Find if the file have been read completely||EOF( )|
// The function returns TRUE
//if the end of file had been reached.
|data = file.readline( )|
if len(data) == 0:
//End of file if the line read is empty.
//Pseudocode DECLARE total, grade: INTEGER <- 0 OPENFILE Grades.txt FOR READ WHILE NOT EOF("Grades.txt") DO //Yes, the parameter is a STRING! READFILE Grades.txt, grade total <- total + grade ENDWHILE CLOSEFILE Grades.txt
#Python total, grade = 0, 0 file = open("grades.txt", "r") grade = "-" while len(grade) != 0: grade = file.readline() if len(grade) != 0: #Yes, I want to use break too... total += int(grade) file.close()