Lesson Objective
Learn how to store, create, edit and open files in Python.
KS3, GCSE, A-Level Computing Resources
Many programs or scripts execute quickly and then terminate. However, unless we retain the output they produce, their efforts become futile.
To achieve 'data persistence', we aim to store the data generated by a program for future use.
This can be accomplished using various methods, including text files, binary files (such as images or sound), databases, and browser cookies. In our code, we read from and write/appended to these storage mechanisms.
When developing data-collecting programs, it's essential to store the data for future use. One common approach is to create a text file and save it in the same directory as your Python file.
Text files are used to store a variety of data:
"r" - Read - Default value. Opens a file for reading, error if the file does not exist.
"w" - Write - Opens a file for writing, creates the file if it does not exist.
"a" - Append - Opens a file for appending, creates the file if it does not exist.
"x" - Create - Creates the specified file, returns an error if the file exists.
The “Open” command must be used to open files. The file is stored in a file object (f). File is opened in “Write” mode. It's good practice to close the file after use.
f = open("Txt_File.txt","w") f.write("Theres something in the file.\nCan we be friencs now?") f.close()
You can use read() to display all the content of the file line by line.
f = open("Txt_File.txt","r") print(f.read()) f.close()
Theres something in the file. Can we be friencs now?
readlines() displays all the content of a file as an array. This can be stored in a. Variable.
f = open("Txt_File.txt","r") print(f.readlines()) f.close()
['Theres something in the file.\n','Can we be friencs now?']
Here is a text file:
Steps:
f = open("Txt_File.txt","r") print(f.readlines()) f.close() print(shopping) shopping[3] = "Carrots\n" print("") f = open("Txt_File.txt","w") f.writelines(shopping) f.close() print(shopping)
['Apples\n', 'Banana\n', 'Pear\n', 'Egg\n', 'Milk\n', 'Bread\n', 'Orange\n', 'Pasta\n', 'Rice'] ['Apples\n', 'Banana\n', 'Pear\n', 'Carrots\n', 'Milk\n', 'Bread\n', 'Orange\n', 'Pasta\n', 'Rice']
???
f = open("new_Txt_File.txt","x")