A file object is Python’s handle for working with a named file. Opening a file creates this object, which software can read line by line or read as one complete string. section 23.3 section 29.2
A simple file-reading workflow is:
- Create a file object with open, supplying the filename and, when needed, a reading mode such as 'r'. section 23.3
- Read each line with a loop or read the entire file into a string. section 23.3 section 29.2
- Pass the collected data to functions for cleaning, storage, analysis, or comparison. section 23.0 section 29.8
- Close the file object after use and test each function before combining it with others. section 23.3
Reading a complete text file
def read_text(filename): inFile = open(filename, 'r') line = inFile.read() return line text = read_text("sonnet18.txt") print(text) The function receives a filename, opens it, reads all contents into a string, returns that string, and prints the result. A separate friends.txt example opens a file object, passes it to read_file(), prints returned names and phone numbers, and then closes it.
The file’s structure determines how the program reads it. A friends.txt file can alternate names and phone numbers, while document comparison can read each file into a string before breaking words into lists and counting them in dictionaries. section 23.3 section 29.0 section 29.8







