Junior — Middle
What methods can be used to read data from a file in a program?
sobes.tech AI
Answer from AI
In Python, there are several methods to read data from a file:
- Read the entire file at once:
with open('file.txt', 'r', encoding='utf-8') as f:
data = f.read()
- Read line by line:
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()
- Read using the
read(size)method:
with open('file.txt', 'r', encoding='utf-8') as f:
chunk = f.read(1024) # read the first 1024 bytes
Using the with statement ensures the file is closed after reading. Choose the appropriate method depending on the task.