Search code examples
pythonappendnewlinereadfilewritefile

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.

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

Solution

  • You're not appending to each line, you're just appending @vtestcom to the end of the file each time through the loop.

    You need to reopen the file in write mode, not append mode, and write each x from the original readlines().

    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:

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