Reading Text from a File
Everything we have done so far only adds text to a text file and closes the file.
Nothing is displayed (printed) on our screens. Now we want to take information from a text file and display it on our screens. Notice how the code below on line 1 when opening a file passes ‘r’ for read after the name of the text file being opened.
file = open('wrestlers.txt', 'r') names = file.readlines() file.close() print(names)
Try to open the text file in the Python editor below and print out all the names.
You can also sort the names by adding the Python sort function.
sorted(names) #sorts a-z sorted(names, reverse=True) #sorts z-a #to print out the sorted information you could simply print one of the above lines. EG: print(sorted(names))
Removing the \n from each line
Whenever we read a file and print the text we also see the ‘\n‘ print alongside each name.
We want every item in the text file to print on a new line and without the ‘\n‘.
The rstrip() method in the code tells Python to strip the white space at end of every line. This also includes the \n.
So for every line in the wrestler names text file, it will print the line and strip \n.
file = open('wrestlers.txt', 'r') names = file.readlines() file.close() for name in names: print(name.rstrip())
Try the code above in the interactive code editor below.
Use the Python editor above to try and display the names from the text file in alphabetical order (A-Z) and than also display the names from Z to A.