gpt4 book ai didi

python - 追加和读取相同的文件 - Python

转载 作者:行者123 更新时间:2023-12-03 21:13:41 25 4
gpt4 key购买 nike

卡在这个学校问题上,我错过了什么?

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



在我的多次尝试中:
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")

如果我让解释器不抛出错误,在几次尝试中它只会打印 5。

最佳答案

此代码应该工作:

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

关于python - 追加和读取相同的文件 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61978372/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com