简体   繁体   中英

Add comma at end of each line in text file from start

I have a text file that has 15 lines of sentences, like this:

Hello Guys
Wassap Guys
Bye Guys

In Python I want to open the file and add comma , at end of each line Like this:

Hello Guys,
Wassap Guys,
Bye Guys,

Here's what I tried:

f = open("ddd.txt", "r+")
tl = f.readlines()

for i in tl:
     f.write(",\n")

You can simply read all lines of your file and rewrite them appending a comma at the end of each line. First you should read the file and save each of its' lines:

filepath = "myfile.txt"
with f as open(filepath):
    lines = f.read().splitlines()

Now you have created a list with every line in your file. Then, you simply rewrite it and append the comma to each line:

with f as open(filepath, "w"):
    for line in lines:
        f.write(line + ",\n")

Hope this was helpful!

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