Different Ways to Read Data from File
There are different ways to read the content of a text file. While Python simplifies the process of reading text files, at times it can still be tricky. The following tested examples summarises three ways to read the content of a text file from a folder.
The .txt file is taken from the online book - A Tale of Two Cities, by Charles Dickens, found at https://www.gutenberg.org/.
Reading a File Line by Line
# Reading a File Line by Line
file = "./MyData/tale-of-two-cities.txt"
filehandle = open(file, 'r', encoding='utf8')
while True:
line = filehandle.readline()
if not line:
break
print(line)
filehandle.close()
Reading a File as Chunks of Lines
# Reading a File as Chunks of Lines
from itertools import islice
file = "./MyData/tale-of-two-cities.txt"
filehandle = open(file, 'r', encoding='utf8')
num_of_lines = 6
with filehandle as input_file:
line_cache = islice(input_file, num_of_lines)
for current_line in line_cache:
print(current_line)
filehandle.close()
Reading a Specific Line from a File
# Reading a Specific Line from a File
file = "./MyData/tale-of-two-cities.txt"
filehandle = open(file, 'r', encoding='utf8')
line_number = 300
print("line %i of %s is:\n" % (line_number, file))
with filehandle as input_file:
current_line = 1
for line in input_file:
if current_line == line_number:
print(line)
break
current_line += 1
filehandle.close()
Reading the Entire File at Once using the function read()
# Reading the Entire File at Once
file = "./MyData/tale-of-two-cities.txt"
filehandle = open(file, 'r', encoding='utf8')
with filehandle as input_file:
content = filehandle.read()
print(content)
filehandle.close()
Reading the Entire File at Once using the function readlines()
# Reading the Entire File at Once
file = "./MyData/tale-of-two-cities.txt"
filehandle = open(file, 'r', encoding='utf8')
with filehandle as input_file:
content = filehandle.readlines()
for line in content:
print(line)
filehandle.close()
Reference:
https://stackabuse.com/reading-files-with-python/