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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20273889/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:04:04  来源:igfitidea点击:

Python Add string to each line in a file

pythonstring

提问by Pcntl

I need to open a text file and then add a string to the end of each line.

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

So far:

迄今为止:

appendlist = open(sys.argv[1], "r").read()

回答by Guy Gavriely

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')

回答by Tim Wilder

def add_str_to_lines(f_name, str_to_add):
    with open(f_name, "r") as f:
        lines = f.readlines()
        for index, line in enumerate(lines):
            lines[index] = line.strip() + str_to_add + "\n"

    with open(f_name, "w") as f:
        for line in lines:
            f.write(line)

if __name__ == "__main__":
    str_to_add = " foo"
    f_name = "test"
    add_str_to_lines(f_name=f_name, str_to_add=str_to_add)

    with open(f_name, "r") as f:
        print(f.read())

回答by José Tomás Tocino

Remember, using the +operator to compose strings is slow. Join lists instead.

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

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)