Python Add string to each line in a file

2020-06-08 12:58发布

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

标签: python string
3条回答
对你真心纯属浪费
2楼-- · 2020-06-08 13:37
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())
查看更多
唯我独甜
3楼-- · 2020-06-08 13:41
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')
查看更多
▲ chillily
4楼-- · 2020-06-08 13:51

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) 
查看更多
登录 后发表回答