Reading and writing

When using the open() function with the + argument (r+, w+, a+) you can both read the contents and write into the file. Because of this you need to keep in mind the current position of the file pointer. Think of the file pointer like the cursor in Microsoft Word. If you start typing, the letters appear at the cursor’s position. The same thing happens with writing to a file, the contents start at the file pointer’s position. Each character written moves the files pointer along. When you read from a file it reads the character at the file pointer’s position and then moves it forward 1.

With r+ and w+ the file pointer will be at the start of the file when you open it, with a+ it will be at the end of the file when you open it. You can find the current position of the pointer using the tell() function.

lines_in_file = []

with open("data2.txt", "r+") as input_file:
    print("The current position is",input_file.tell())
    line = input_file.readline()
    while line:
        lines_in_file.append(line)
        print("The current position is",input_file.tell())
        line = input_file.readline()

Gives an output of:

The current position is 0
The current position is 25
The current position is 42
The current position is 62
The current position is 87
The current position is 103
The current position is 123

Why don’t the numbers match the number of characters on each line? Remember the hidden new line character \n. The above code was run on Windows which adds an additional character \r which is a carriage return to each line. If the file had been generated on Mac or Linux the values would be:

The current position is 0
The current position is 24
The current position is 40
The current position is 59
The current position is 83
The current position is 98
The current position is 117

To move the file pointer you use the seek() function.

input_file.seek(42)

This would place the file pointer at the start of the third line in the data2.txt file Windows example.


Open up write.py and change it to read:

with open("HelloWorld.txt", "r+t") as file_handler:
    line1 = file_handler.readline()
    print("The position after reading line 1 is " + str(file_handler.tell()))
    file_handler.seek(5)
    file_handler.write("XX" + "\n")
    file_handler.seek(0)
    line1 = file_handler.readline()
    line2 = file_handler.readline()
print("File altered")

Check the output file and see what is different from before.

Report a Glow concern
Cookie policy  Privacy policy

Glow Blogs uses cookies to enhance your experience on our service. By using this service or closing this message you consent to our use of those cookies. Please read our Cookie Policy.