Junior — Middle
What methods can be used to read data from a file on disk?
sobes.tech AI
Answer from AI
In Python, there are several ways to read data from a file on disk:
- Read the entire file at once:
with open('file.txt', 'r', encoding='utf-8') as f:
data = f.read()
print(data)
- Line-by-line reading:
with open('file.txt', 'r', encoding='utf-8') as f:
for line in f:
print(line.strip())
- Read into a list of lines:
with open('file.txt', 'r', encoding='utf-8') as f:
lines = f.readlines()
print(lines)
- Reading with the
read(size)method for chunked reading:
with open('file.txt', 'r', encoding='utf-8') as f:
chunk = f.read(1024) # read the first 1024 bytes
print(chunk)
Using the with statement ensures the file is closed after reading. The encoding is specified for proper handling of text files.