D
D
Davidd20082021-08-02 20:19:33
Python
Davidd2008, 2021-08-02 20:19:33

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

3 answer(s)
M
Michael, 2021-08-02
@David2008

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) # перезапись файла

V
Vindicar, 2021-08-02
@Vindicar

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().

D
Dmitry, 2021-08-02
@LazyTalent

1. Read the file
2. Go through all the lines and append the value
3. Save the new data to a new file

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question