How to read a file in Python
This article shows how to read a text file in Python.
Table of contents
- 1. Read a file using open() and close()
- 2. Read a file using with statement
- 3. Read a file using try-finally
- 4. Read a file line by line
- 5. Read a file and skip the first line
- 6. Default open mode
r
- 7. Download Source Code
- 8. References
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.
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
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.
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
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
['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
love your content man