Answer the question
In order to leave comments, you need to log in
How to append text to an existing file in python?
I have a txt file that contains the following text:
dakdasjlkas:dsadsakj54fsf
dakdasjlkas:dsadsakj54fsf
adsdasjlkas:dsadsakj545sf
how do I add some text to the end of each line?
I tried like this but this flag appends on new lines :(
for i in range(3):
with open('1.txt', 'a') as file:
file.write('input')
Answer the question
In order to leave comments, you need to log in
text = 'input' # фраза, которая будет дописана в конец строки
output = '' # инициализация результирующего текста
with open('1.txt', 'r') as file:
for line in file: # считывание текущего файла
output += (line.replace('\n', '') + text + '\n')
with open('1.txt', 'w') as file:
file.write(output) # перезапись файла
At the end of each line - no way. Think for yourself, there are no lines in the file, it is a sequence of bytes. It's just that some programs break this sequence into sections according to the line feed character.
So to insert something in the middle of the file, you would have to move forward the entire contents of the file after that place.
It's easier to do otherwise: create a new file next to the old one, read the old one line by line, write the changed lines to the new one. And then delete the old one and rename the new one to the old one.
For the last part, look at the os module, specifically os.unlink() and os.rename().
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question