AppDividend
Latest Code Tutorials

How To Read File In Python Example | Python File Read

0

In Python, there is no need to import an external library to read and write files. Python provides the inbuilt function for creating, writing, and reading files. In this tutorial, we will see how to read file in Python.

First, we will see how to open a file using Python open() function and then read the files. Before we start reading the file, let’s understand how to create a file in Python, and then we will write and read the file.

Python Create File

Content Overview

We can create a new file in Python using the open() method, with one of the following parameters:

“x” – Create – will create the file, 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

In this blog, I have already written how to write a file in Python.

We will use the Python writelines() method to write in a file.

Python file method writelines() 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.

Python’s writelines() method writes the items of the list 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 will be 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 Open and Read File

We can open the file using a built-in open() function.

The open() function returns the file object that has a read() method for reading the content of the file.

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

By default, Python read() method returns the whole text, but you can also 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

Now, let’s say we want to read the first 14 characters from the above file.

To achieve that output, we can pass the parameter in the read function.

# 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

By calling readline() two times, you can read the two first lines.

# 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 sizehint argument is present, instead of reading up to EOF, whole lines totaling approximately sizehint 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 line by line, it will separate each line and present the file in the readable format.

But if there is a complex data file which is not readable, this piece of code could be useful.

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 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. open() has a single required argument that is the path to the file. 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 make sure 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 be closed eventually.

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 make sure that your code behaves in a way that is well defined 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 what the try-finally block is, check out Python Exceptions.

Python with statement

In Python, the “with statement“, you get better syntax and exceptions 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 for ensuring that a clean-up 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 with statement automatically takes care of closing the file once it leaves the with 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 for you.

Finally, How To Read File In Python Example | Python File Read Tutorial is over.

Related Posts

File handling in Python

Write Python dictionary to CSV

Leave A Reply

Your email address will not be published.

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