添加和读取同一文件 - Python

问题描述 投票:0回答:1

被这道学校题卡住了,我还缺什么?

"目标:完成将给定的新数据追加到指定文件中,然后打印文件内容的函数。"完成函数,将给定的新数据追加到指定的文件中 然后打印文件的内容"

在我的多次尝试中。

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

测试案例,预期输出。Hello World

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

如果我让解释器不出错,在几次尝试中,它就会直接打印5。

python
1个回答
3
投票

这段代码应该可以用。

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

1
投票

你可以用... a+ 读写模式。在您使用 write您可以使用以下方法将光标移动到初始位置 seek 方法,然后从头开始读取。

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

1
投票

你可以用 a+ 来赋予你的程序读取权限。

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

编辑:正如评论者所指出的,你需要在文件中寻找到0的位置,这样你就可以读取整个文件了

© www.soinside.com 2019 - 2024. All rights reserved.