Main Tutorials

How to read a file in Python

This article shows how to read a text file in Python.

Table of contents

P.S Tested with Python 3.8

1. Read a file using open() and close()

In Python, we can use open() to open a file, and close() to close a file. Forget to close the file will cause memory or resource leak.

file.txt

welcome to python 1
welcome to python 2
welcome to python 3
welcome to python 4

f = open("C:\\Users\\mkyong\\projects\\python\\io\\file.txt")
print(f.read())
f.close()

Output

Terminal

welcome to python 1
welcome to python 2
welcome to python 3
welcome to python 4

2. Read a file using with statement

The with statement will automatically close the file once it leaves the with block.


filename = "C:\\Users\\mkyong\\projects\\python\\io\\file.txt"
with open(filename) as f:
    print(f.read())

3. Read a file using try-finally

We also can close the file at the finally block.


filename = "C:\\Users\\mkyong\\projects\\python\\io\\file.txt"
f = open(filename)
try:
    print(f.read())
finally:
    f.close()

4. Read a file line by line

4.1 We can use readlines() to read a file line by line.


with open("file.txt") as f:
    lines = f.readlines()
    for line in lines:
        print(line)

Output – The print() default adds a new line.

Terminal

welcome to python 1

welcome to python 2

welcome to python 3

welcome to python 4

4.2 We can add an end='' to the print() to prevent the default newline.


with open("file.txt") as f:
    lines = f.readlines()
    for line in lines:
        #print(line)
        print(line, end='') # prevent add a newline

Output

Terminal

welcome to python 1
welcome to python 2
welcome to python 3
welcome to python 4

5. Read a file and skip the first line

The below example read a file, skip the first line, and store the rest of the file content to a variable.


line = []                    # list
with open("file.txt") as f:
    line = f.readlines()[1:] # skip the first line, store in line variable

print(line)

Output

Terminal

  ['welcome to python 2\n', 'welcome to python 3\n', 'welcome to python 4']

6. Default open mode `r`

The r is the default open mode, so, both open("file.txt") and open("file.txt", "r") do the same thing.

7. Download Source Code

$ git clone https://github.com/mkyong/python

$ cd io

8. References

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
sandeep
2 years ago

love your content man