I have a text file. I would like to use python v3.6 to read the text file line by line, append each line with a sub-string and replace the existing line with the appended string line by line.
To be clearer, here is the original text file;
1,2,3
4,5,6
The desired output text file should look like this;
appended_text,1,2,3
appended_text,4,5,6
This is how my code looks like;
with open(filename, 'r+') as myfile:
for line in myfile:
newline = "appended_text" + "," + line
myfile.write(newline)
I did not get what I want. What I got instead was a huge line of text appended at the end of the file. How should the code be modified? Is there a better way to implement what I want?