Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python将字符串添加到文件中的每一行_Python_String - Fatal编程技术网

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

Python将字符串添加到文件中的每一行,python,string,Python,String,我需要打开一个文本文件,然后在每行末尾添加一个字符串 到目前为止: appendlist = open(sys.argv[1], "r").read() 请记住,使用+操作符来编写字符串是很慢的。改为加入列表 file_name = "testlorem" string_to_add = "added" with open(file_name, 'r') as f: file_lines = [''.join([x.strip(), string_to_add, '\n']) for

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

到目前为止:

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

请记住,使用
+
操作符来编写字符串是很慢的。改为加入列表

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) 

首先,阅读
open
的文档。我尝试了这个方法,但没有添加字符串,而是将它放在另一行。请注意,该行上有一个ip。因此,它应该是127.0.0.1字符串,而不是127.0.0.1(返回/输入)字符串。如果f中x的
[''.join([x.strip(),string_to_add,'\n'])
?将open(file_name,'w')作为f:f.writelines(file_行)不应该是:将open(output,'w')作为f:f.writelines(file_行)?否,因为同一个文件应该被覆盖,但现在您提到它,
输出
变量未使用。
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())
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)