如何在第一行末尾添加文本

时间:2019-01-20 01:55:30

标签: python python-3.x

with open ("a.txt", "a+") as f:
    f.write("Hello ")

当前,这将进入文本文件,如下所示。

hello
hello

我也尝试过

for line in f:
    f.write(line.replace("\n", ""))

那没有用。

有什么想法吗?

3 个答案:

答案 0 :(得分:2)

with open('a.txt', 'r') as istr, open('output.txt', 'w') as ostr:
    for i, line in enumerate(istr):
        # Get rid of the trailing newline (if any).
        line = line.rstrip('\n')
        if i == 0:
            line += 'Hello'
        print(line, file=ostr)

答案 1 :(得分:1)

也许使用:

with open ("a.txt", "r") as f, open ("b.txt", "w") as f2:
    f2.write(f.read().rstrip()+"hello ")
    os.rename("b.txt", "a.txt")

答案 2 :(得分:1)

这是对我有用的@ U9-Forward代码的编辑版本。

with open ("a.txt", "r") as f, open ("b.txt", "w") as f2:
    f2.write(f.read().rstrip()+"hello ")
    os.remove("a.txt")
    os.rename("b.txt", "a.txt")