Issue
so I have a txt file that I am required to add a phrase at every end of the line. Note that the phrase is the same added on every line
soo what I need is
here are some words
some words are also here
vlavlavlavlavl
blaaablaabalbaaa
before
here are some words, the end
some words are also here, the end
vlavlavlavlavl, the end
blaaablaabalbaaa, the end
after
i also tried this method
with open("Extracts.txt", encoding="utf-8") as f:
for line in f:
data = [line for line in f]
with open("new.txt", 'w', encoding="utf-8") as f:
for line in data:
f.write(", Deposited")
f.write(line)
but the word was shown at the beginning of the line and not the end.
Solution
line
ends with a newline. Remove the newline, write the line and the addition, followed by a newline.
There's also no need to read the lines into a list first, you can just iterate over the input file directly.
with open("Extracts.txt", encoding="utf-8") as infile, open("new.txt", 'w', encoding="utf-8") as outfile:
for line in infile:
line = line.rstrip("\n")
outfile.write(f"{line}, Deposited\n")
Answered By - Barmar
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.