我需要在文本文件的每一行的末尾写()文本。如何将光标指向特定行的末尾。
注意:seek(0,2)会将我放在文件的末尾,但我需要每行的结尾。
感谢帮助人员 - 我已经结合您的解决方案来实现我的需求:
AllLines = [ (str.rstrip('\n') + 'Val2' + "\n" ) for str in AllLines ]
然后我可以将AllLines写入新的输出文件。
答案 0 :(得分:3)
您需要分两步完成此操作。由于创建新文件更安全,您可以:
with open("input.txt") as infile, open("output.txt", "w") as outfile:
for line in infile:
outfile.write(line.rstrip("\n") + "added text\n")
答案 1 :(得分:2)
new_lines = []
with open("my_file") as f:
new_lines = [line.strip("\n")+"some_ending_stuff" for line in f]
with open("my_file","w") as f:
f.write("\n".join(new_lines))
类似的东西应该起作用