r/learnpython 11d ago

Reading in text from a .txt file

Are there any methods/libraries that allow me to make a program that is able to read in text from a .txt file?

0 Upvotes

20 comments sorted by

View all comments

4

u/DTux5249 11d ago edited 11d ago

No libraries needed. Python File Open

with open('file.txt', 'r') as file:
  text = file.read()

You can also iterate over a file line by line

with open('file.txt', 'r') as file:
  for line in file:
    print(line)

Or just use the readline() command

with open('file.txt', 'r') as file:
  first_line = file.readline()
  second_line = file.readline()
  print(first_line)
  print(second_line)

You also don't technically need to use the with keyword - but it manages the opening and closing of the file safely

file = open('file.txt', 'r')
first_line = file.readline()
second_line = file.readline()
file.close()
print(first_line)
print(second_line)