Nono.MA

Read Text from a File with Python

LAST UPDATED JANUARY 31, 2023

Here's how to read text from a file in Python; maybe a file that already exists or a file to which you wrote the text with Python.

Read file contents

my_file = open('/your/file.txt', 'r')

# Read all file contents
contents = my_file.read()

# Print the contents
print(contents)

# Close the file
my_file.close()

Read file contents as lines

my_file = open('/your/file.txt', 'r')

# Read the lines of the file
lines = my_file.readlines()

# Iterate through the lines
for line in lines:
  print(line)

file.close()

BlogCodePython