Reading Files in Python

Python provides built-in functions to read from files.

with open("example.txt", "r") as file:
  content = file.read()
  print(content)
  • open() opens the file.
  • "r" stands for read mode.
  • with ensures the file is closed automatically after use.

You can also read line by line:

with open("example.txt", "r") as file:
  for line in file:
    print(line.strip())
← PrevNext →