Skip to content

File Handling

File handling allows a Python program to interact with files, including reading, writing, and updating them. Python provides a variety of builtin functions and methods to handle files efficiently.

File Handling Science

The built-in open() function is used to open a file. It requires a filename and a mode as arguments and returns a file object. The close() method should always be called when you’re done with the file.

file = open("example.txt", "r") # Opens the file in read mode
# ... operations ...
file.close() # Closes the file

File Modes: The mode determines how a file is used. It is specified as a second argument to the open() function.

ModeDescription
rOpens a file for reading only. The file pointer is at the beginning. This is the default mode.
rbOpens a file for reading in binary format.
r+Opens a file for both reading and writing. The file pointer is at the beginning.
rb+Opens a file for both reading and writing in binary format.
wOpens a file for writing only. It overwrites the file if it exists. If not, it creates a new file.
wbOpens a file for writing in binary format.
w+Opens a file for both writing and reading. It overwrites the file if it exists, or creates a new one.
wb+Opens a file for both writing and reading in binary format.
aOpens a file for appending. The pointer is at the end of the file. It creates a new file if it doesn’t exist.
abOpens a file for appending in binary format.
a+Opens a file for both appending and reading. The pointer is at the end of the file. It creates a new file if it doesn’t exist.
ab+Opens a file for both appending and reading in binary format.

Once a file is open, you can read content using these methods:

  • read(): Reads the entire file content into a single string.
  • readline(): Reads a single line from the file.
  • readlines(): Reads all lines into a list of strings.

To write content, use:

  • write(string): Writes a single string to the file.
  • writelines(list_of_strings): Writes a list of strings to the file.

The with statement is the recommended way to handle files. It automatically closes the file, even if an error occurs, so you don’t have to manually call close().

with open("example.txt", "r") as file:
content = file.read()
print(content)
# The file is automatically closed here