Skip to main content

Python File Input/Output Operations

A file is essentially a container on a computer where data can be stored.

To be able to access the information, it needs to firstly be opened. Once we have finished using it, it must then be closed for the resources linked with the file to be released.

Let's see how to handle files in Python!

How To Open Files in Python

Python has a built-in open() function that allows you to open a file for either reading or writing.

note

This function creates an object which can be used to access other methods related to it. It is necessary to use the open() command before you can read or write any file.

For example, consider the following test.txt text file:

This is a test file.
Hello world from the test file.

and then we can open the test.txt file in the following way:

# open file in current directory
my_file = open("test.txt")
note

In the above code, open() function create a file object named my_file.

This object can be used to work with files and directories.

By default, the files are open in read mode (i.e. they can't be modified). In fact, the previous code is equivalent to:

my_file = open("test.txt", "r")

Different Modes to Open a File in Python

The syntax of open() function is:

file_object = open(file_name [, access_mode][, buffering])

where:

  • file_name: a string value that contains the name of the file that you want to access
  • access_mode: the mode in which the file has to be opened (read, write, append, etc.).
    • It is optional.
    • A complete list of possible values is given in the table below.
  • buffering:
    • If value is set to 0, no buffering takes place.
    • If value is set to 1, line buffering is performed while accessing a file.
    • If value is set to a value greater than 1 then buffering action is performed with the indicated buffer size.
    • If value is set to a negative number, the buffer size is the system default.
ModeDescription
rOpen a file for reading. (default)
wOpen a file for writing. Creates a new file if it does not exist or truncates the file if it exists.
xOpen a file for exclusive creation. If the file already exists, the operation fails.
aOpen a file for appending at the end of the file without truncating it. Creates a new file if it does not exist.
tOpen in text mode. (default)
bOpen in binary mode.
+Open a file for updating (reading and writing)

Note that they can be combined with each other, resulting in, for example:

ModeDescription
rbOpen a file for reading only in binary format. The file pointer is placed at the beginning of the file.
r+Open a file for both reading and writing. The file pointer placed at the beginning of the file.
rb+Open a file for both reading and writing in binary format. The file pointer placed at the beginning of the file.
wbOpen a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
w+Open a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.
wb+Open a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.
abOpen a file for appending in binary format. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
a+Open a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.
ab+Open a file for both appending and reading in binary format. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.

How To Close Files in Python

When you close a file in Python, you're essentially allowing the resources it was using to be released, which can then be used elsewhere.

This is done with the help of the close() method: it flushes any unwritten information and closes the file object.

# open a file
my_file= open("test.txt", "r")

# do some operations ...

# close the file
my_file.close()
note

After you perform file operation, you should always close the file!

This is a good programming practice.

warning

When a file is closed, you must open it again to perform operations with it!

Open and Close files with with open Syntax

In Python, we can use the with...open syntax to automatically close the file.

For example:

with open("test.txt", "r") as my_file:
read_content = my_file.read()
print(read_content)

How To Read Files in Python

To read the contents of a file, the read() method is used once the file has been opened.

The syntax of read() method is:

file_object.read([count])

where:

  • file_object is the opened file to read
  • count is an optional parameter that specifies the number of bytes to be read from the opened file

For example:

# open a file
my_file = open("test.txt", "r")

# read the file
read_content = my_file.read()
print(read_content)

Output

This is a test file.
Hello world from the test file.

Explanation: We begin by opening the file called test.txt and then employ the read() function of the File object named my_file to store its contents in a variable called read_content.

How To Write Files in Python

To write into a file in Python, we must first open it in write mode by giving "w" as a second argument to open(). Then, we can use the write() method to write into the file.

The syntax of read() method is:

file_object.write(string)

where:

  • file_object is the opened file to write
  • count is the content to be written into the opened file

For example, write "Hello World!\n" string in the test2.txt file:

# Open a file
my_file = open("test2.txt", "wb")
my_file.write("Hello World!\n")

# Close opend file
my_file.close()

Explanation: First, open the test2.txt file (if it does not exist, it is created) and then use the read() function of the File object named my_file to write the string. Finally, the file is closed.

warning
  • If we try to open a file that doesn't exist, a new file is created.
  • If a file already exists, its content is erased, and new content is added to the file.
  • The write() method does not add a newline character ('\n') to the end of the string.

How To Rename Files in Python

Python os module provides methods that help you perform file-processing operations, including renaming files.

The syntax is:

os.rename(current_filename, new_filename)

where:

  • current_filename is the file that you want to rename
  • new_filename is the new filename

For example:

import os

# Rename a file from test1.txt to test2.txt
os.rename("test1.txt", "test2.txt")

Handling Exception in Python Files

If an exception occurs when we are performing some operation with the file, the code exits without closing the file.

A safer way is to use a try...finally block.

try:
my_file = open("test.txt", "r")
read_content = my_file.read()
print(read_content)
finally:
# close the file
my_file.close()
note

The file is closed in the finally block as finally always executes, and the file will be closed even if an exception occurs.

Summary of Python File Methods

In Python, the file object provides a range of functions for handling files, such as opening and closing them, as well as reading and writing to them.

Here is the complete list of methods in text mode with a brief description:

MethodDescription
close()Closes an opened file. It has no effect if the file is already closed.
detach()Separates the underlying binary buffer from the TextIOBase and returns it.
fileno()Returns an integer number (file descriptor) of the file.
flush()Flushes the write buffer of the file stream.
isatty()Returns True if the file stream is interactive.
read(n)Reads at most n characters from the file. Reads till end of file if it is negative or None.
readable()Returns True if the file stream can be read from.
readline(n=-1)Reads and returns one line from the file. Reads in at most n bytes if specified.
readlines(n=-1)Reads and returns a list of lines from the file. Reads in at most n bytes/characters if specified.
seek(offset,from=SEEK_SET)Changes the file position to offset bytes, in reference to from (start, current, end).
seekable()Returns True if the file stream supports random access.
tell()Returns an integer that represents the current position of the file's object.
truncate(size=None)Resizes the file stream to size bytes. If size is not specified, resizes to current location.
writable()Returns True if the file stream can be written to.
write(s)Writes the string s to the file and returns the number of characters written.
writelines(lines)Writes a list of lines to the file.