How to Create, Open, Write, and Read File in Python

Python provides an inbuilt function for creating, writing, and reading files.

Python Create File

To create a file in Python, use the open() function. The open() is a built-in Python function that creates a new file with the following parameters.

“x” – Create – will create the file and returns an error if the file exists.

“a” – Append – will create the file if the specified file does not exist.

“w” – Write – will create the file if the specified file does not exist.

See the following code.

# app.py

f = open("data.txt", "a")

The above code creates a file if the file does not exist.

Now, let’s write two lines in the file.

Python write file

To write a file in Python, use the writelines() function. The writelines() is a built-in function that writes the sequence of strings to the file.

The sequence can be any iterable object producing strings, typically the list of strings. There is no return value. Instead, the writelines() method writes the list items to the file.

Where the texts will be inserted depends on the file mode and stream position.

  1. “a”: The texts will be inserted at a current file stream position, default at the end of the file.
  2. “w”: The file will be emptied before the texts are inserted at the current file stream position, default 0.

See the following code to write a file.

# app.py

f = open("data.txt", "a")
f.writelines(["\nSee you soon!", "\nPeek-a-boo."])
f.close()

After you run the above code, you will get the file named data.txt with the following content.

# data.txt

See you soon!
Peek-a-boo.

The next step is to open and read a file.

Python read file

To read a file in Python, use the open() and read() functions. The open() function returns the file object with a read() method for reading the file’s content.

We have a file called data.txt, which has the following content written in it.

See you soon!
Peek-a-boo.

Now, we will open this file using the following code.

f = open('data.txt', 'r')

Now, read the content and print it on the console.

# app.py

f = open('data.txt', 'r')
print(f.read())

Output

➜  pyt python3 app.py
See you soon!
Over and out.
➜  pyt

How to read-only parts of the File in Python

To read only parts of a file in Python, use the read() function. The read() method returns the whole text, but you can specify how many characters you want to return.

Let’s say we have the following file named sample.txt. It has the following content.

This is line 1
This is line 2
This is line 3
This is line 4
This is line 5
This is line 6
This is line 7
This is line 8
This is line 9
This is line 10
This is line 11

We want to read the first 14 characters from the above file.

We can pass the parameter in the read function to achieve that output.

# app.py

f = open('sample.txt', 'r')
print(f.read(14))

Output

➜  pyt python3 app.py
This is line 1
➜  pyt

Python Read Lines

You can return one line by using the readline() method.

# app.py

f = open('sample.txt', 'r')
print(f.readline())

Output

➜  pyt python3 app.py
This is line 1

➜  pyt

You can read the first two lines by calling the readline() function two times.

# app.py

f = open('sample.txt', 'r')
print(f.readline())
print(f.readline())

Output

➜  pyt python3 app.py
This is line 1

This is line 2

➜  pyt

Python readlines()

Python file method readlines() reads until EOF using the readline() and returns the list containing the lines.

If the optional size hint argument is present, instead of reading up to EOF, whole lines totaling approximately size hint bytes (possibly after rounding up to the internal buffer size) are read.

The empty string is returned only when EOF is encountered immediately.

See the following example.

# app.py

f = open('sample.txt', 'r')
print(f.readlines())

Output

➜  pyt python3 app.py
['This is line 1\n', 'This is line 2\n', 'This is line 3\n', 'This is line 4\n', 'This is line 5\n', 'This is line 6\n', 'This is line 7\n', 'This is line 8\n', 'This is line 9\n', 'This is line 10\n', 'This is line 11']
➜  pyt

When you run the code for reading the file or document, it will separate each line and present the file in a readable format.

But this code could be helpful if a complex data file is not readable.

Read data using for loop.

By looping through the lines of the file, you can read the whole file, line by line.

# app.py

f = open('sample.txt', 'r')
for x in f:
    print(x)

Output

➜  pyt python3 app.py
This is line 1

This is line 2

This is line 3

This is line 4

This is line 5

This is line 6

This is line 7

This is line 8

This is line 9

This is line 10

This is line 11
➜  pyt

Opening and closing a file with a try-catch block

When you want to work with a file, the first thing to do is to open it. This is done by invoking the open() built-in function.

The open() function has a required argument: the file’s path. The open() has a single return, the file object:

f = open('data.txt')

After you open a file, the next thing to learn is how to close it.

Warning: You should always ensure that an open file is closed correctly.

It’s important to remember that it’s your responsibility to close the file. In most cases, upon the termination of an application or script, a file will eventually be closed.

However, there is no guarantee when exactly that will happen. This can lead to unwanted behavior, including resource leaks.

It’s also a best practice within Python (Pythonic) to ensure that your code behaves in a well-defined way and reduces any unwanted behavior.

When you’re manipulating the file, there are two ways that you can use to ensure that a file is closed correctly, even when encountering an error. The first way to close a file is to use the try-finally block.

See the following code.

# app.py

try:
    f = open('sample.txt', 'r')
    print(f.readlines())
finally:
    f.close()

If you’re unfamiliar with the try-finally block, check out Python Exceptions.

Python with statement

The “with statement” in Python gets better syntax and exception handling. 

Python with statement simplifies exception handling by encapsulating standard preparation and cleanup tasks. Also, it will automatically close the file.

Python “with statement” provides a way to ensure that cleanup is always used.

See the following code.

# app.py

with open('sample.txt') as reader:
  data = reader.read()
  print(data)

Output

➜  pyt python3 app.py
This is line 1
This is line 2
This is line 3
This is line 4
This is line 5
This is line 6
This is line 7
This is line 8
This is line 9
This is line 10
This is line 11
➜  pyt

The statement automatically closes the file once it leaves the block, even in cases of error.

You can use a with statement as much as possible, as it allows for cleaner code and makes handling any unexpected errors easier.

That’s it.

Related Posts

How to create a file if it does not exist

File handling in Python

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.