Sobes.tech
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:

  1. Read the entire file at once:
with open('file.txt', 'r', encoding='utf-8') as f:
    data = f.read()
  1. Read line by line:
with open('file.txt', 'r', encoding='utf-8') as f:
    for line in f:
        print(line.strip())
  1. Read into a list of lines:
with open('file.txt', 'r', encoding='utf-8') as f:
    lines = f.readlines()
  1. 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.

What methods can be used to read data from a file in… - sobes.tech