Python将字符串添加到文件中的每一行

Pcn*_*ntl 13 python string

我需要打开一个文本文件,然后在每行的末尾添加一个字符串.

至今:

appendlist = open(sys.argv[1], "r").read()
Run Code Online (Sandbox Code Playgroud)

Jos*_*ino 13

请记住,使用+运算符组合字符串很慢.改为加入列表.

file_name = "testlorem"
string_to_add = "added"

with open(file_name, 'r') as f:
    file_lines = [''.join([x.strip(), string_to_add, '\n']) for x in f.readlines()]

with open(file_name, 'w') as f:
    f.writelines(file_lines) 
Run Code Online (Sandbox Code Playgroud)


Guy*_*ely 11

s = '123'
with open('out', 'w') as out_file:
    with open('in', 'r') as in_file:
        for line in in_file:
            out_file.write(line.rstrip('\n') + s + '\n')
Run Code Online (Sandbox Code Playgroud)