Text files
Text files allow us to store and load data such that information can be retained between uses of the program e.g. a high score file for a game.
Reading a textfile
Once you have opened a textfile in read mode you can use the read() or readline() commands to read some or all of the textfile. The read command generally reads the whole textfile as a string including new line characters
(\n). You can pass a number as a parameter to read a specific number of characters e.g. file.read(10) would read the first 10 characters of the file.
You can also apply the split() command and pass the new line character as a parameter. This will result in an array where each new line is an element in the array.
Example
file = open("names.txt") names = file.read().split("\n") file.close() |
The code above would read the open file and create a list where each line of the text file is an item in the list. There are several other ways to achieve the same outcome.
Writing to a textfile
If you choose the write option then you overwrite what was previously stored in the text file and if you open with the append option then you will add your text to the end of the file. Regardless of which method you choose,
you can use the write() command to write to the text file. To create a new line you need to add a new line character.
Example
names = ["Bob","Joe","Sam"] file = open("names.txt","w") for name in names: if name != names[len(names)-1]: file.write(name + "\n")
else: file.write(name) file.close() |
The code above writes each new name to a new line in the text file and the if statement ensures the last name does not create a new line.
Closing files
You may have noticed in the examples above that each time we have done what we needed with the file we close it. This is good practice i.e. always close files as soon as you can.
The eval command
Another useful trick for storing a list in a textfile is to use the str() and eval() methods. The eval() method evaluates a string as Python code. This means we can simply write the string version of a list to a text file
to store it and then read avd evaluate the stored value when we want to retrieve it.
Example
names = ["Bob","Joe","Sam"] file = open("names.txt","w") file.write(str(names)) file.close()
file = open("names.txt") names = eval(file.read()) file.close() |
The code above writes a list with full syntax as a string to a text file and then when it reads it back in evaluates the string and so names conatains a fully functioning Python list.
Syntax checker
Fix the code below so that the two subroutines allow you to read the current story stored on a text file or add to it.
def read_story(): |
file = open("story.txt") # added file handle to store open file |
print(file.read()) # readline corrected to read |
file.close() # added file close |
|
def write_story(): |
file = open("story.txt", "a") # fixed open type from w to a |
new_line = input("Enter a new line for the story: ") |
file.write(" " + new_line) # added space so sentences don.t start right next to each other. |
file.close() # corrected from story.close to file.close |
|
choice = 0 |
while choice != 3: |
choice = int(input("Choose 1. Read story 2. Add to story 3. Close")) |
if choice == 1: |
read_story() # it is a procedure so does not get stored anywhere |
elif choice == 2: |
write_story() # it is a procedure so does not get stored anywhere |
else: |
print("Thanks for playing endless story") |