Python File Operation

A file is a named location used for storing data. For example, main.py is a file that is always used to store Python code.

Python provides various functions to perform different file operations, a process known as File Handling.


Opening Files in Python

In Python, we need to open a file first to perform any operations on it—we use the open() function to do so. Let's look at an example:

Suppose we have a file named file1.txt.

Opening a File in Python
Opening a File in Python

To open this file, we can use the open() function.

file1 = open("file1.txt")

Here, we have created a file object named file1. Now, we can use this object to work with files.

More on File Opening

Different File Opening Modes

Python allows us to open files in different modes (read, write, append, etc.), based on which we can perform different file operations. For example,

file1 = open("file1.txt")

Here, we are opening the file in the read mode (we can only read the content, not modify it).

Note: By default, Python files are open in read mode. Hence, the code open("file1.txt", "r") is equivalent to open("file1.txt").

Different Modes to Open a File in Python

Mode Description
r Open a file in reading mode (default)
w Open a file in writing mode
x Open a file for exclusive creation
a Open a file in appending mode (adds content at the end of the file)
t Open a file in text mode (default)
b Open a file in binary mode
+ Open a file in both read and write mode

Here are a few examples of opening a file in different modes,

# open a file in default mode (read and text)
file1 = open("test.txt")      # equivalent to open("test.txt", "rt")

# open a file in write and text mode 
file1 = open("test.txt",'w')  

# open a file in read, write and binary mode
file1 = open("img.bmp",'+b') 
Opening a File Using its Full Path

We can also open a file using its full path.

file_path = "/home/user/documents/file1.txt"
file1 = open(file_path)

In this example, /home/user/documents/file1.txt is a full path to a file named file1.txt located in the /home/user/documents/ directory.

Note: To learn more about directories, please visit Python Directory.


Reading Files in Python

After we open a file, we use the read() method to read its content. For example,

Suppose we have a file named file1.txt.

Reading a File in Python
Reading a File in Python

Now, let's read the content of the file.

# open a file in read mode
file1 = open("file1.txt")

# read the file content
read_content = file1.read()
print(read_content)

Output

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

In the above example, the code file1.read() reads the content of the file and stores it in the read_content variable.

Note: If you need clarification about how the code file1.read() works, please visit Working of Python Objects.


Writing to Files in Python

To write to a Python file, we need to open it in write mode using the w parameter.

Suppose we have a file named file2.txt. Let's write to this file.

# open the file2.txt in write mode
file2 = open('file2.txt', 'w')

# write contents to the file2.txt file
file2.write('Programming is Fun.\n')
file2.write('Programiz for beginners\n')

When we run the above code, we will see the specified content inside the file.

Writing to a Python File
Writing to a Python File
Be Careful While Writing to a File

If we try to perform the write operation to a file that already has some content, the new content will replace the existing ones. For example,

Suppose we have a file named file2.txt.

Writing to a Python File
Writing to a Python File

Now let's write to this file.

# open the file2.txt in write mode
file2 = open('file2.txt', 'w')

# write new contents to the file2.txt file
file2.write('Learning Python is interesting.\n')
file2.write('File operations are useful.\n')

When we run the above code, the new content will replace any existing content in file2.txt.

Writing to an Existing Python File
Writing to an Existing Python File

Note: If we try to open a file that doesn't exist, a new file is created, and the write() method will add the content to the file.


Closing Files in Python

When we are done performing operations on the file, we need to close the file properly. We use the close() function to close a file in Python. For example,

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

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

# close the file
file1.close()

Output

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

Note: Closing a file will free up the resources that are tied to the file. Hence, it is a good programming practice to always close the file.


Opening a Python File Using with...open

In Python, there is a better way to open a file using with...open. For example,

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

Output

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

Here, with...open automatically closes the file, so we don't have to use the close() function.

Note: Since we don't have to worry about closing the file, make a habit of using the with...open syntax.


More on Python File Operations

Exception Handling in Files

If an exception occurs while working with a file, the code exists without closing the file. Hence, it's a good practice to use the try...finally block.

Let's see an example.

try:
    file1 = open("file1.txt", "r")
    read_content = file1.read()
    print(read_content)

finally:
    # close the file
    file1.close()

Output

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

Here, the finally block is always executed, so we have kept the close() function inside it. This ensures that the file will always be closed.

To learn more about exceptions, visit Python Exception Handling.

Note: Make a habit of using the with...open syntax while working with files so you don't have to worry about closing the file.

Some Commonly Used File Methods

There are various methods available with a file object. Some of them have been used in the above examples.

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

Method Description
close() Closes an opened file
read(n) Reads the file content
seek(offset,from=SEEK_SET) Changes the file position to offset bytes, in reference to from (start, current, end)
tell() Returns an integer that represents the current position of the file's object
write(s) Writes a string to the file
writelines(lines) Writes a list of lines to the file

Video: Reading and Writing Files in Python

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges