python 如何在文本文件的每个数字后面附加一个字符串?

cvxl0en2  于 2022-12-28  发布在  Python
关注(0)|答案(1)|浏览(133)

我有一个电话号码列表,每一个都在一个新行上,我想在每一个新行的末尾附加一个字符串“@ 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())

我希望每行打印如下

7163737373@vtest.com
7156373737@vtest.com

对于新行上的所有文件。
但我得到了这个

7163737373
7156373737@vtest.com,vtest.com
eh57zj3b

eh57zj3b1#

你不是在每一行都追加,你只是在每次循环中把@vtestcom追加到文件的末尾。
您需要以写模式而不是追加模式重新打开文件,并从原始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())

仅供参考,这在bash中要容易得多:

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

相关问题