A
A
Alexey2020-10-31 14:33:41
Python
Alexey, 2020-10-31 14:33:41

How to open a txt file to edit one specific line, while leaving all the rest unchanged?

Hello, the problem is this ...
I'm making a telegram bot for myself. When you click on the "Edit" button, the bot writes "Enter the line you want to edit" (in this case, you could enter not the entire line but a part)
I already implemented the search for part of the line like this

str = message.text
        sub_string = str
        with open("data.txt") as file:
            lines = file.readlines()

        for line in lines:
            if sub_string in line:
                bot.send_message(message.chat.id, line)

Now you need to do something that would search for the desired string according to the same principle, after which the bot asks you to enter what you need to fix it and replaces the found string with the one that we enter ...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Dugin, 2020-10-31
@resolut1123

In the lines list, modify the desired line lines[i] and save lines back to a file. To save the file, you will need to open it in write mode. In general, of course, for such tasks it is better to use a database. Look in the direction of working with at least SQLite3, everything is simple there.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question