Search code examples
pythonfiletext

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")

Solution

  • 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 open(filepath) as f:
        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 open(filepath, "w") as f:
        for line in lines:
            f.write(line + ",\n")
    

    Hope this was helpful!