You have 3 free guides left 😟
Unlock your guides
You have 3 free guides left 😟
Unlock your guides

14.1 Reading from files

2 min readjune 24, 2024

Python's file input/output capabilities allow you to read from and write to files on your computer. This powerful feature enables you to work with external data, store program results, and manage persistent information across program executions.

The function is the gateway to file operations in Python. By understanding different file modes and reading methods, you can efficiently handle various file types and sizes, while proper closing practices ensure resource management and data integrity.

File Input/Output in Python

File opening with open()

  • Use the
    open()
    function to open a file and obtain a
    • Syntax:
      file_object = open(file_path, mode)
      • file_path
        represents the path to the file as a string (
        'data.txt'
        )
      • mode
        specifies how the file should be opened, default is ' for read mode (
        'r'
        ,
        '[rb'](https://www.fiveableKeyTerm:rb')
        )
  • Common read modes:
    • 'r': read mode (default), opens the file for reading only, at the beginning
    • 'rb': binary read mode, used for reading non-text files (images, audio)
  • Ensure the file exists and has read permissions to avoid
    FileNotFoundError
    or
    [PermissionError](https://www.fiveableKeyTerm:PermissionError)
  • Consider the (absolute or relative) when opening files

Reading methods for file contents

  • [read()](https://www.fiveableKeyTerm:read())
    reads the entire contents of a file as a single string
    • Syntax:
      file_contents = file_object.read()
    • Returns an empty string when reaching the end of the file
  • [readline()](https://www.fiveableKeyTerm:readline())
    reads a single line from the file
    • Syntax:
      line = file_object.readline()
    • Returns an empty string at the end of the file
    • Useful for reading large files line by line to avoid memory issues
  • [readlines()](https://www.fiveableKeyTerm:readlines())
    reads all lines of a file and returns them as a list of strings
    • Syntax:
      lines = file_object.readlines()
    • Each line becomes an element in the list (
      ['line1\n', 'line2\n']
      )
    • Useful for processing file contents line by line
  • File pointer advances after each read operation, subsequent reads continue from the current position
  • Be aware of when reading lines from a file

Proper file closing practices

  • Always close files after reading or writing to free up system resources
    • Syntax:
      file_object.close()
  • Closing a file ensures:
    • All data is written to the file (for write operations)
    • File resources are released back to the operating system
    • Other programs can access the file without conflicts
  • Use a
    [try-finally](https://www.fiveableKeyTerm:try-finally)
    block to ensure the file is always closed, even if an exception occurs
    • Syntax:
      try:
          file_object = open(file_path, mode)
          # Perform file operations
      finally:
          file_object.close()
      
  • Alternatively, use a
    with
    statement () to automatically close the file after the block
    • Syntax:
      with open(file_path, mode) as file_object:
          # Perform file operations
      

Additional File Operations

  • : Use
    file_object.seek()
    to move the file pointer to a specific position
  • : Control how data is buffered when reading or writing files
  • : Specify the text encoding when opening files (e.g., UTF-8, ASCII)
© 2024 Fiveable Inc. All rights reserved.
AP® and SAT® are trademarks registered by the College Board, which is not affiliated with, and does not endorse this website.


© 2024 Fiveable Inc. All rights reserved.
AP® and SAT® are trademarks registered by the College Board, which is not affiliated with, and does not endorse this website.

© 2024 Fiveable Inc. All rights reserved.
AP® and SAT® are trademarks registered by the College Board, which is not affiliated with, and does not endorse this website.
Glossary
Glossary