我想在我的文件中的每一行附加一些文本
这是我的代码
filepath = 'hole.txt'
with open(filepath) as fp:
line = fp.readline()
cnt = 1
while line:
#..........
#want to append text "#" in every line by reading line by line
text from .txt file
line = fp.readline()
cnt += 1
最佳答案
您可以阅读这些行并将它们放入列表中。然后您以写入模式打开同一个文件,并在每一行中写入您要追加的字符串。
filepath = "hole.txt"
with open(filepath) as fp:
lines = fp.read().splitlines()
with open(filepath, "w") as fp:
for line in lines:
print(line + "#", file=fp)
关于python - 在 python 中将字符串附加到 .txt 文件的每一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50268298/