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

  1. Read the entire file at once:
with open('file.txt', 'r', encoding='utf-8') as f:
    data = f.read()
print(data)
  1. Line-by-line reading:
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()
print(lines)
  1. 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.

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