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

时间:2013-11-28 19:54:24

标签: python string

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

到目前为止:

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

3 个答案:

答案 0 :(得分: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')

答案 1 :(得分:11)

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

output = ""
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) 

答案 2 :(得分:2)

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