Python File Handling

In this post we’ll discuss Python’s File handling methods. The following code examples show how to create, read, write and delete files in Python.

How to Create Files in Python

To create a file in Python, we use the open() method, which takes two parameters: name of the file and any one of the modes: 'x', 'a', 'w'.

'x' is used to create a new file. An error is thrown if the file exists. 'a' and 'w' are used for appending to a file and writing to a file, respectively, however if the file doesn’t exist, then the file is created.

Example:

file = open("somefile.txt", "x")

A new file somefile.txt is created.

How to Read Files in Python

To read a file in Python, we use the open() function, passing in the name of the file and 'r' for reading mode.

Example: read a file called somefile.txt

Contents of the somefile.txt:

Hello!!
Welcome to Python
Goodbye.
file = open('somefile.txt', 'r')
print(file.read())
file.close()

Output:

Hello!!
Welcome to Python
Goodbye.

How to Read Parts of a File in Python

We can read parts of the file by pass in the number of characters to read() method. For example:

file = open('somefile.txt', 'r')
print(file.read(5))
file.close()

Output:

Hello

How to Read a File Line By Line

We can use the readline() method to read each line of the file.

Read Only One Line

file = open('somefile.txt', 'r')
print(file.readline())
file.close

Output:

Hello!!

Read Two Lines

file = open('somefile.txt', 'r')
print(file.readline())
print(file.readline())
file.close

Output:

Hello!!

Welcome to Python

Read All The Lines

We can use the for loop to read all lines of the file:

file = open('somefile.txt', 'r')
for x in file:
    print(x)

Output:

Hello!!

Welcome to Python

Goodbye

How to Write to a File in Python

To write to a file, we again use the open() method with the file name as the first parameter and either 'a' or 'w' as the second parameter.

'a' will append data to an existing specified file. 'w' will overwrite data on the specified file.

In both cases, the file is created if it doesn’t exist.

Write to a New File

file = open('writefile.txt', 'w')
file.write("Write some content!")
file.close()

Output:

writefile.txt is created with contents:

Write some content!

Append Content to an Existing File

To append contents to an existing file, we need to pass in the 'a' parameter to the open() method for append mode.

file = open('writefile.txt', 'a')
file.write("\nWrite more content!")
file.close()

Contents of the writefile.txt file:

Write some content!
Write more content!

How to Delete Files in Python

To delete files, we must import the os module and use the remove() method:

import os
if os.path.exists("writefile.txt"):
    os.remove("writefile.txt")

The above method first checks to see if the file exists before attempting to delete it. An error is thrown if the file doesn’t exist.