open is Python’s built-in function for opening a file and creating a file object. Give it a filename string; the file should be in the same folder as the Python program. section 23.3
Open and read a text file
friends_file = open('friends.txt') (names, phones) = read_file(friends_file) print(names) print(phones) friends_file.close() The first line opens friends.txt. The resulting file object is passed to read_file, which reads the data. Close the file when finished. section 23.3
Listing 29.1. Reading a file
def read_text(filename):
""" #1
filename: string, name of file to read #1
returns: string, contains all file contents #1
""" #1
inFile = open(filename, 'r') #2
line = inFile.read() #3
return line #4
text = read_text("sonnet18.txt") #5
print(text)
Compare a reusable function that opens a filename, reads the entire file into a string, returns it, and prints the result. section 29.2
Remember these practical points:
- Use open(filename, 'r') when explicitly opening a file for reading. section 29.2
- Test file-reading functions and inspect their returned data before connecting them to other functions. section 23.3








