liveBook · Manning

File object

As explained in Get Programming: Learn to code with Python

A named unit of data stored on a computer and read or written by software.

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

How Get Programming: Learn to code with Python covers it

How deep it goes
Demonstrates opening, iterating, reading, closing, testing, and passing file contents to functions without discussing file-system internals.
Examples
Uses friends.txt with names and phone numbers, and sonnet18.txt as a complete text document.
What it assumes
Assumes basic Python functions, variables, strings, and tuples while teaching file opening and reading through small examples.
What you can do after
Operate Python’s open function to read files, store their contents, close file objects, and supply data to analysis functions.
How it connects
Connects file objects with Python functions, strings, tuples, lists, dictionaries, and data cleaning.

Also explained in

Compare how 8 books explain file object →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Get Programming: Learn to code with Python. The section links point to the parts of the book it draws on.