Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/shell/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编辑一个.txt文件,我想在每个数字后粘贴一个特定的字符串_Python_Txt - Fatal编程技术网

如何使用python编辑一个.txt文件,我想在每个数字后粘贴一个特定的字符串

如何使用python编辑一个.txt文件,我想在每个数字后粘贴一个特定的字符串,python,txt,Python,Txt,9418012345,你好,世界 9418154321,你好,世界 94xxxxxxxx,你好,世界 . . . . . . . 1000个手机号码,但信息相同。 我已经把手机号码贴在每一行了。如何在所有数字后添加逗号和相同的消息。您可以读取文件行并将其存储在字符串列表中,然后将字符串添加到所有行: text_to_add = ', hello world' with open('numbers.txt') as f: lines = f.read().splitlines()

9418012345,你好,世界
9418154321,你好,世界
94xxxxxxxx,你好,世界
.
.
.
.
.
.
.
1000个手机号码,但信息相同。

我已经把手机号码贴在每一行了。如何在所有数字后添加逗号和相同的消息。

您可以读取文件行并将其存储在字符串列表中,然后将字符串添加到所有行:

text_to_add = ', hello world'    

with open('numbers.txt') as f:
    lines = f.read().splitlines()
with open('result_file.txt', "w") as f:
    for line in lines:
        print(line + text_to_add, file=f)

阅读内容并通过添加所需的消息在行上迭代,然后使用新内容再次将其写入文件

message = "HelloWorld"
with open("number.txt") as fd:
    lines = fd.read().splitlines()
    
with open("file_with_text.txt","w") as fd:
    for line in lines:
        print(f'{line}, {message}', file=fd)


逐行读取只有数字的文件。用字符串将新行一行一行写到另一个文件中。将第一个文件替换为第二个文件。谢谢,它只需稍微调整wrt下一行和空格
message = "HelloWorld"
with open("number.txt") as fd:
    lines = fd.read().splitlines()
    
with open("file_with_text.txt","w") as fd:
    for line in lines:
        print(f'{line}, {message}', file=fd)