You are currently viewing Python: How to Read Text Files

Python: How to Read Text Files

The code example demonstrates how to read files and handle errors in Python. You should look at this code if you’re new to using files in Python. It shows you how to read files line by line using a for loop, how to automatically close files using the with statement, and how to use try/except blocks to catch common file-related problems:

# the file to read from
filename: str = 'memo.txt'


if __name__ == '__main__':

    try:

        # 'with' statement ensures the file is automatically closed when done
        with open(filename) as file:

            # read file line by line
            for line in file:
                print(line, end='')

        # print success message
        print(f"\nSuccessfully read from file '{filename}'.")

    except OSError as e:
        print(f"Could not open file '{filename}': {e.strerror}.")

If you’re interested in learning how to create and write to files in Python, be sure to check out another one of my articles titled How to Write Text to a File in Python.

I sincerely hope that you find this code helpful. If you wish to learn more about Python, please subscribe to our newsletter today and continue your Python learning journey with us!

Leave a Reply