如何将字符串附加到文本文件上的每个数字?



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

您不是在每行后面附加,您只是在每次循环中将@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.comn')
with open("demofile.txt", "r") as y:
print(y.read())

仅供参考,这在bash中更容易做到:

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

最新更新