我编写了以下 python 代码片段,将小写的 p 字符附加到 txt 文件的每一行:
f = open('helloworld.txt','r')
for line in f:
line+='p'
print(f.read())
f.close()
但是,当我执行这个 python 程序时,它只返回一个空白:
zhiwei@zhiwei-Lenovo-Rescuer-15ISK:~/Documents/1001/ass5$ python3 helloworld.py
谁能告诉我我的代码有什么问题吗?
最佳答案
目前,您仅读取每一行,而不写入文件。以写入模式重新打开文件并将完整字符串写入其中,如下所示:
newf=""
with open('helloworld.txt','r') as f:
for line in f:
newf+=line.strip()+"p\n"
f.close()
with open('helloworld.txt','w') as f:
f.write(newf)
f.close()
关于python - 使用python将字符附加到txt文件中的每一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47276506/