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:
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 these resources to learn about new commands for this level and to help you meet the success criteria.
x = open(y, z)
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.
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 = y.read()
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.
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.