请记住,使用+
运算符组合字符串很慢.改为加入列表.
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)
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')