Reading and writing to text files.
Select the button below to open the Python program in a new window. Run the program and read the lines of code to see if you can understand how it works. It will be helpful to arrange your display so that you can have this browser window on one side of the screen and the code on the other.
Watch this video to learn about the new concepts shown in the program:
The new commands used in this program and others that may be useful. Select them below to learn more:
x is a pointer to the file y with the data flow z.
The data flow can be:
“r” reading data from the file. The file must already exist otherwise the program will crash.
“w” writing data to the file, overwriting all data already storted in the file. If no file exists a new one is created.
“a” writing data to the end of a file (appending) without overwriting data already in the file.
“c” creating a new file. Which is not necessary if you are also going to write data to the file. Use “w” instead.
Data can only flow in one file in one direction at a time. It is possible to have two files open, one to read and one to write.
x is assigned the data in file pointer y. The file must be opened with an `”r”` flow first.
Note data may include character codes, for example end of line characters. Use the `.strip()` method to remove invisible character codes from the data read from a file.
Write y to file pointer x.
Note if you want data to be written on a new line, you must include the end of line character code `\n`.
Close the file pointer x. File should be closed as soon as possible. Not closing files can in some cases corrupt the file.
Questions to think about with this program to check your understanding:
Identify a new line character in the program.
\n is a new line character. Also called a line feed or end of line marker. It is an example of what is known as an “escape code”. These are signals to a device to execute a text command rather than print or display the text characters.
Change the program so that:
Hello, I don’t believe we have met.
What is your name? Dave
Nice to meet you Dave.
It’s good to see you again, Dave.
Use the flowcharts if you need more support in understanding the steps required to meet the criteria. Use the Parsons code sorting exercise only if you are really stuck.
Check your program works by removing the data in the datafile.txt file and running the program. Note, do not delete the file otherwise the program will not work.
Run the program for a second time to verify the data was saved and loaded correctly.