简体   繁体   English

append 一个字符串如何指向文本文件中的每个数字?

[英]How can append a string to every number on a text file?

I have a phone number list,each on a new line and I want to append a string “@ctest.com” to the end of every new line.我有一个电话号码列表,每个都在一个新行上,我想要 append 一个字符串“@ctest.com”到每个新行的末尾。

with open(“demofile.txt”, “r”) as f1: 
    Lines = f1.readlines()
    For x in Lines:
     f= open(“demofile.txt”, “a”)
     f.writelines([“@vtest.com”])
     f.close()

    y = open(“demofile.txt”, “r”)
Print(Y.read())

I was expecting each line to print as below我期待每一行打印如下

7163737373@vtest.com
7156373737@vtest.com

For all the files on new lines.对于新行上的所有文件。

But I got this但我得到了这个

7163737373
7156373737@vtest.com,vtest.com

You're not appending to each line, you're just appending @vtestcom to the end of the file each time through the loop.您没有附加到每一行,您只是在每次循环时将@vtestcom附加到文件的末尾。

You need to reopen the file in write mode, not append mode, and write each x from the original readlines() .您需要以写入模式而不是 append 模式重新打开文件,并从原始readlines()写入每个x

with open("demofile.txt", "r") as f1: 
    lines = f1.readlines()

with open("demofile.txt", "w") as f:
    for line in lines:
        f.write(f'{line.strip()}@ctest.com\n')

with open("demofile.txt", "r") as y:
    print(y.read())

FYI, this is much easier to do in bash:仅供参考,这在 bash 中更容易做到:

sed -i 's/$/@vtest.com' demofile.txt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM