This is an archived version of the course. Please see the latest version of the course.

Handling text files

Python makes reading from and writing to files easy.

I will assume you have a file called test.txt in your current directory.

Here is how you would read the whole file in one go. Not recommended if the file is large!

# Open a file in read mode, and read everything into content
with open("test.txt", "r") as infile: 
    content = infile.read()

open() returns a file object and is assigned to the infile variable. The with statement will automatically close the file once you exit the block, so you do not have to worry about that!

You can also read the file one line at a time using a loop. This method is memory efficient because it reads and processes each line individually. This means you do not have to read the whole file into memory at once.

# Note that each line ends with an '\n' intact.
# Use line.strip() to remove any leading/trailing whitespace
with open("test.txt", "r") as infile: 
    for line in infile:
        print(line.strip())   

To write to a file, use the write() method of the file object. Remember to also open the file in write mode!

# Remember to open the file in write mode
with open("output.txt", "w") as outfile:
    outfile.write("First line\n")
    outfile.write(str(2) + "\n")
    outfile.write(f"{3}rd line\n")