追加和读取相同文件-Python

卡在这个学校问题上,我想念什么?

“目标:完成将给定的新数据附加到指定文件,然后打印文件内容的功能”

在我的许多尝试中:

import os
def appendAndPrint(filename, newData):
    with open(filename, 'a') as f:
        f = f.write(newData)
        r = f.read()
        print(f)
测试用例,预期输出:Hello World
with open("test.txt", 'w') as f: 
    f.write("Hello ")
appendAndPrint("test.txt", "World")

如果我让解释器没有抛出错误,则在几次尝试中,它只会输出5。

评论
  • Oo晓oO
    Oo晓oO 回复

    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 = f.append(newData)
    ...
    

    Make sure you also use f.append instead of f.write

  • snihil
    snihil 回复

    此代码应工作:

    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())