简体   繁体   中英

How to add lines one by one from one file into another file

I have one file called ClientList.txt that has a output of:

client1.hello.com
client2.hello.com
client3.hello.com

I want to append these lines one by one with additional text into my other file called output.txt using python.

Example of what I want to achieve in my output.txt file:

clients name: client1.hello.com, clients URL: client1.hello.com, service: VIP
clients name: client2.hello.com, clients URL: client2.hello.com, service: VIP
clients name: client3.hello.com, clients URL: client3.hello.com, service: VIP

Can someone help me achieve this?

What I tried so far:

def main():

f= open("output.txt","w+")

for i in range(3):
    f.write("clients name: client1.hello.com, clients URL: client1d.hello.com, service: VIP")
f.close()

Output I get:

clients name: client1.hello.com, clients URL: client1d.hello.com, service: VIPclients name: client1.hello.com, clients URL: client1d.hello.com, service: VIPclients name: client1.hello.com, clients URL: client1d.hello.com, service: VIP

I am new to python, so I am not sure on how to aproach this.

You can do it like this in Python:

with open("ClientList.txt", "r") as infile:
    with open("output.txt", "w") as outfile:
        for line in infile:
            outfile.write("".join(["clients name: ",line.strip(), ", clients URL: ", line.strip(), ", service: VIP\n"]))

Content in output.txt :

clients name: client1.hello.com, clients URL: client1.hello.com, service: VIP
clients name: client2.hello.com, clients URL: client2.hello.com, service: VIP
clients name: client3.hello.com, clients URL: client3.hello.com, service: VIP

Again, seeing that you edited your post, in order for your code to work your should change the write line to the following:

f.write("clients name: client1.hello.com, clients URL: client%d.hello.com, service: VIP\n" % (i+1))

That should do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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