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.
CodePudding user response:
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")
CodePudding user response:
You can first get all the lines in the text file using the readlines
method, and then add the line you want to.
with open("Extracts.txt", encoding="utf-8") as f:
data = f.readlines()
new_data = []
for line in data:
line = line.replace("\n", "")
line = " , Deposited\n"
new_data.append(line)
with open("new.txt", "w", encoding="utf-8") as f:
f.writelines(new_data)
CodePudding user response:
As mkrieger1 already said, the order of operations here is wrong. You are writing the ", Deposited" to the file before you're writing the content of the line in question. So a working version of the code swaps those operations:
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(line.strip())
f.write(", Deposited\n")
Note that I also added a strip() function to handling the line of text, this removes whitespaces at the start and end of the string to get rid of any extra line changes before the ", Deposited". Then the line change was manually added to the end of the string as a string literal "\n".