liveBook · Manning

File object

As explained in Python How-To

A file is a persistent, named container of data stored by a computer system.

Need to process a saved task list? A file stores the data; a Python file object is the stream returned by open() that lets you read or write it. The object reports properties such as its name, mode, and encoding. The mode matters: the default 'r' permits reading, not writing. section 11.1.1

Use `with open("tasks.txt") as file:` for ordinary reads. Work with `file` inside the block; it closes when the block ends. This is preferable to relying on a separate `close()` call, which is easy to forget. section 11.1.1

Listing 11.2 Using with to open a file
with open("tasks.txt") as file:     #1
    print(f"file object: {file}")
    data = file.read()
    print(data)
 
# output the following lines:
file object: <_io.TextIOWrapper name='tasks.txt' mode='r' encoding='UTF-8'>
1001,Homework,5
1002,Laundry,3
1003,Grocery,4

Open a task file, print the file object, and read its contents within a with block. section 11.1.1

Choose a reading method to fit the job:

  • `read()` returns all text as one string; avoid loading an entire large file when memory is a concern. section 11.1.1 section 11.1.2
  • `for line in file` processes one line at a time. Strip its line break before splitting fields; `readline()` takes one line when that is all you need. section 11.1.2
  • `readlines()` makes a list of lines when the file is small enough and you want to modify the resulting list. section 11.1.2
Listing 11.3 Reading the file as a generator
from collections import namedtuple
 
Task = namedtuple("Task", "task_id title urgency")           #1
 
with open("tasks.txt") as file:
    for line in file:
        stripped_line = line.strip()                         #2
        task_id, title, urgency = stripped_line.split(",")   #3
        task = Task(task_id, title, urgency)
        print(f"{stripped_line}: {task}")
 
# output the following lines:
1001,Homework,5: Task(task_id='1001', title='Homework', urgency='5')
1002,Laundry,3: Task(task_id='1002', title='Laundry', urgency='3')
1003,Grocery,4: Task(task_id='1003', title='Grocery', urgency='4')

Each task row is stripped, split on commas, and converted to a task record as the file is iterated. section 11.1.2

To save text, open with 'w' and call `write()` for a string or `writelines()` for a sequence. Write mode can create and truncate a file; use 'a' to append instead. `writelines()` does not insert line breaks, so include them in the strings yourself. Writing through a file opened in default read mode raises an error. section 11.1.3

Listing 11.6 Writing to a new file
with open("tasks_new.txt", "w") as file:    #1
    print("File:", file)
    result = file.write(data)
    print("Writing result:", result)
 
# output the following lines:
File: <_io.TextIOWrapper name='tasks_new.txt' mode='w' encoding='UTF-8'>
Writing result: 45

Writing task data to a new text file returns the number of characters written. section 11.1.3

A file object can also connect to a binary file: `pickle.dump()` receives one opened with 'wb' to preserve Python objects. Moving, copying, or selecting files by modification time is a different task—it acts on files as whole items rather than reading their contents. section 11.3.1 section 11.4

How Python How-To covers it

How deep it goes
Works through opening, closing, reading methods, writing methods, and modes, without examining stream implementation internals.
Examples
Uses task rows to demonstrate reading, line-by-line record creation, writing, and appending.
What it assumes
Introduces opening and closing from the basics while drawing on loops, generators, lists, and string splitting.
What you can do after
Operate/configure it to read task data efficiently, save text, append records, and close streams reliably.
How it connects
Links file objects to context managers, iterators, lists, file modes, and pickling.

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 Python How-To. The section links point to the parts of the book it draws on.