C
C
cenox2021-01-26 20:18:28
Python
cenox, 2021-01-26 20:18:28

How to make deletion from .txt file?

VK BOT
Hello, there is a command that, when used, adds the peer_id of the conversation to the .txt file, so how do I make the command remove the already existing peer_id from the .txt file?
Script:

@bot.on.message(lower=True, text=['givevip <id>', 'вип <id>'])
async def adminpanel(ans: Message, id):
    if ans.from_id in admins:
        id = int(id)
        id +=2000000000
        id = str(id)
        with open('donaters.txt', encoding="utf8") as file:
            dlist = file.read().splitlines()
        if id in dlist:
            return f"У беседы № {id} уже есть випка."
        with open('donaters.txt', "a", encoding="utf8") as f:
            f.write(id + "\n")
            await ans(f"Вы выдали випку беседе № {id}")

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alan Gibizov, 2021-01-26
@cen0x

my_id = '012345'
with open('file.txt', 'r') as input_file:
    input_file = input_file.read().replace(f'{my_id}\n','')
with open('file.txt', 'w') as output_file:
    output_file.write(input_file)

Here's the recipe for you. It's not perfect, but it works quite well.

A
Antosha Styazhkin, 2021-01-26
@desulaid

You can remove it using the os package and the remove()
method os.remove(path_to_file)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question