2️⃣

20.2 Text Files

Text Files

One way to do this is with text files. Python supports opening text files without the need for importing any modules. To do this, just do:
myfile = open("mytext.txt","w")
 
In this, you’ll notice that the first parameter for the open function is the file we would like to open. The second parameter is how we would like to open it. These are common ways to open the file. We can use these as the second parameter:
  • “w” stands for “write” - this will create a file if there isn’t already one. It allows you to write on but not read the file. If you open a file that already has data on it using this, all the data on the file will be cleared.
myfile = open("mytext.txt","w")
  • “r” stands for “read” - this will not create a file and not allow you to write on the file. It only supports reading the file. It doesn’t clear the file’s data.
myfile = open("mytext.txt","r")
  • “a” stands for “append” - this will create a file if there isn’t already one. It doesn’t clear the file’s data. It allows you to write (append) data to the file but does not allow you to read the file.
myfile = open("mytext.txt","a")
 
To write to the file, make sure that you open the file in either “w” or “a” mode. Then, it’s as simple as doing: myfile.write(#info) where you can put the information that you would like to write as the parameter. If you need to write more than one time, you can just use another myfile.write(#info). Keep in mind, however, that the write method doesn’t put any spaces between your inputs, meaning that, for the below code, your text file would look like this: hello worldhi again
myfile = open("mytext.txt", "w") myfile.write('hello world') myfile.write('hi again') myfile.close()
 
In addition to this, the write method only supports strings, meaning that you will either have to convert your data to a string using str(#data) or use formatting, like ‘%i’ % #number.
 
To read a file, you can do myfile.read(). This will return the text file’s data. If you would like to use the data, you could do
myfile = open("mytext.txt", "r") mydata = myfile.read()
 
Once you have finished writing your information to the file, you can do: myfile.close(). This closes the file, saving it. This is useful not only at the end of your write but also for appending. After all, since you can’t read a file in append mode, you can close the file then, using the same opening method, open the file in read mode. Basically, always close the file!
 

Other Useful Functions

myfile.readable() will determine whether or not a file is readable. If it is, the function will return True. Otherwise, it will return False:
myfile = open('mytext.txt', 'r') print(myfile.readable()) # determines if myfile is readable
myfile.readline() returns the next line in a file:
myfile = open('mytext.txt', 'r') print(myfile.readline()) # prints the first line print(myfile.readline()) # prints the second line print(myfile.readline()) # prints the third line
myfile.readlines() will return a list of all the lines in a file:
myfile = open('mytext.txt', 'r') print(myfile.readlines()) # ["line one\n", "line two\n", etc.]
myfile.seek() sets your position in a file:
# mytext.txt is a file with the following text: # 1 L0V3 PYTH0N myfile = open('mytext.txt', 'r') myfile.seek(4) # sets your position to the fourth index print(myfile.readline()) # prints the fourth index and everything after it # prints "V3 PYTH0N"
myfile.seekable() checks if it is possible to set your position in a certain file. This function returns True if possible and False if not:
myfile = open('mytext.txt', 'r') print(myfile.seekable()) # determines if you can set your position in myfile
myfile.tell() returns your current position in a file:
myfile = open('mytext.txt', 'r') myfile.seek(5) print(myfile.tell()) # prints 5
myfile.writable() will determine whether or not a file is writable. If it is, the function will return True. Otherwise, it will return False:
myfile = open('mytext.txt', 'r') print(myfile.writable()) # prints False because myfile is on read mode
myfile.writelines() writes a list of lines into a file:
myfile = open('mytext.txt', 'w') myfile.writelines(['line one\n', 'line 2']) # mytext.txt will become the following: # line one # line 2
View code on GitHub.

Practice

Modify Random Text

Import random. Create a program that creates a blank text file and writes a random number (in the form of a string) between 1 and 1000 on it. Next, close the file. Next, open the file again (this time read it) and read the text. Assign a variable to that data. Print the variable, then print the int(variable) * 4.

Hidden Message

Create a program that reads the attached text file (textfile.txt) and writes (appends) 2 newlines and then every 7th word followed by a space onto the text file.
Ex: if the text file contained “hi”, “ho”, “ha”, “hy”, “he”, “hu”, “we”, “everyone” it would write 2 newlines and then ‘hi everyone’
 
⚖️
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.