'Appending string to a line read from file places appended string on next line
I have a .txt file like the following:
abc
def
ghi
Now, I want to add some string behind each row directly. However, my output is:
abc
---testdef
---testghi---test
My code is as follows:
file_read = open("test.txt", "r")
lines = file_read.readlines()
file_read.close()
new_file = open("res.txt", "w")
for line in lines:
new_file.write(line + "---test") # I tried to add "\r" in the middle of them, but this didn't work.
new_file.close()
Solution 1:[1]
What I understood is, you want to add a string behind a string, for example "abcd" should be changed into "---testabcd".
So the mistake you made is in new_file.write(line + "---test"), if you want add string1 before a string2, then you have to specify string1 first then string2.
So change it tonew_file.write("---test" + line)
Tip: Instead of using '+' operator, use f strings or .format.
f"---test{line}"this is f string.
"Hello {friends}".format(friends="myname")
For use of '\r':
Whenever you will use this special escape character \r, the rest of the content after the \r will come at the front of your line and will keep replacing your characters one by one until it takes all the contents left after the \r in that string.
print('Python is fun')
Output: Python is fun
Now see what happens if I use a carriage return here
print('Python is fun\r123456')
Output: 123456 is fun
So basically, it just replaces indexes of string to character after \r.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Faraaz Kurawle |
