Append and Read Same File - Python

Viewed 312

Stuck on this school question, what am I missing?

"Objective: Complete the function to append the given new data to the specified file then print the contents of the file"

On of my many attempts:

import os
def appendAndPrint(filename, newData):
    with open(filename, 'a') as f:
        f = f.write(newData)
        r = f.read()
        print(r)

Test case, expected output: Hello World

with open("test.txt", 'w') as f: 
    f.write("Hello ")
appendAndPrint("test.txt", "World")

If I get the interpreter to not throw an error, on several attempts it would simply print 5.

3 Answers

This code should work:

def append_and_print(filename, new_data):
    with open(filename, "a") as f:
        f.write(new_data)
    with open(filename, "r") as f:
        print(f.read())

You can open the file with a+ to also give your program read permissions:

import os
def appendAndPrint(filename, newData):
    with open(filename, 'a+') as f:
        f.write(newData)
        f.seek(0)
        r=f.read()
        print(r)
...

edit: as commenters pointed out, you need to seek to the 0 position in the file so that you can read the whole thing

You can use a+ mode for reading/writing.
After you append using write,
you can move the cursor to the initial position using seek method,
then read it from the beginning.

def appendAndPrint(filename, newData):
    with open(filename, 'a+') as f:
        f.write(newData)
        f.seek(0)
        print(f.read())


with open("test.txt", 'w') as f:
    f.write("Hello ")
appendAndPrint("test.txt", "World")
Hello World
Related