This is an archived version of the course and is no longer updated. Please find the latest version of the course on the main webpage.

Reading and writing files

Reading a file

You can read the whole file in one go. Not recommended if the file is large!

with open("test.txt", "r") as f:  # Note: open the file in read mode
    content = f.read()

To read a fixed number of characters, use f.read(n), where n is the number of characters to read. The method will read the first n unread characters. It will read the next n unread characters if you invoke the method again.

To read a single line, use f.readline(). Calling this method again will read the next line, and so on.

You can also read the file one line at a time using a loop.

# Note that each line ends with an '\n' intact.
# You may or may not want to keep the '\n' depending on your use case
for line in f:
    print(line)   

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.

Writing to a file

You will need to open your files in write ("w") or append ("a") mode to write to the file. "w" will overwrite the contents of the file if it exists.

f.write(str) accepts a str as its argument. So you will have to convert any other types to a string. This method will also return the number of characters written (if you ever need this information).

with open("test.txt", "w") as f:
    f.write("First line\n")
    f.write(str(2) + "\n")
    f.write(f"{3}rd line\n") 

File tell and seek

The file object usually has a ‘pointer’ that gives it its current location. So after you read a line, the pointer will go to the next line.

When you open your file in "r" mode, your file pointer will be at the beginning of the file.

When you open your file in "a+" mode, your file pointer will be at the end of the file.

After you call f.readline(), your file pointer will be at the beginning of the next line.

To know where you file pointer is currently at, you can use f.tell(), which will return an integer giving you its current location.

To move the pointer to a specific location, use f.seek(offset, from).

  • offset is the number of characters from the from parameter
  • from can be either 0 (beginning of the file), 1 (current pointer position), 2 (end of file; only available for binary files). Defaults to 0.
>>> f = open("test.txt", "w+")   # open new file for reading and writing
>>> f.write("Just\ntesting\nseek\n")
>>> f.tell()  # check pointer's current location
18 # currently at the end of the file
>>> f.seek(5) # let's move it to the 5th character from the beginning
>>> f.read(4) # let's read the next four characters from the pointer's current location
test

I personally have not used all these detailed features (I just read by lines). But remember that they exist if you ever need them.