โ† Home

Read from a File with Python

You can read from a text file in Python using the open function.

View on Egghead

First, create a file with some text in it. Mine is named input.txt and has five lines of lorem ipsum text in it.

We'll, use the open function to open our file: open("input.txt"). This function takes the path to the file as an argument.

We will also use the with keyword, which will automatically close our file at the end of the code block.

The as keyword will allow us to save the file contents to a variable name.

The full line of code to open the file will be:

with open("input.txt") as text:
    pass

Now, we can loop through the lines of text in our "input.txt" file!

with open("input.txt") as text:
    for line in text:
        print("-------")
        print(line)

๐ŸŽ‰ Now we have successfully read the contents of a file in Python!

Here is the full code.

Be the first to know about my posts!

Share this post with a friend!

LinkedIn
Reddit