Python Read Text File
In this tutorial we will learn how to use Python to read a text file with different approach of writing code.
Create test text file
First step we need to create a text file named test.txt in the same folder that we will create Python code file and input below text for testing purpose.
Hello! from toricode.com
This file to test Python text file reading.
Happy Coding!
Read all text of file
To read file in Python we use built-in method open().
Below code example to read all text from file by using method read() from file object.
f = open('test.txt', 'r')
print(f.read())
f.close()
Read file line by line
We can use readline() method to read each line of the text file as below example.
f = open('test.txt', 'r')
print(f.readline())
print(f.readline())
print(f.readline())
f.close()
Looping through the content of file
We can loop the file object to read the text file line by line as below Python code example.
f = open('test.txt', 'r')
for line in f:
print(line)
f.close()
Read Unicode file with UTF-8 encoding
Create a text file named test_unicode.txt with Unicode content as below for testing and located in folder when we save python code file.
Việt Nam
日本
中国
To read unicode file we simply add encoding=‘utf-8’ argument.
f = open('test_unicode.txt', 'r', encoding='utf-8')
for line in f:
print(line)
f.close()