Search code examples
pythoneventsincrementtelethon

Q:how to increment file creation from an event?


I tried to create a txt file for every new message from Telegram using telethon event. I would like to have txt file like OIF ,OIF1, OIF2,OIF3 ... for every message I get

Thanks for help
That's my code

client.start()
@client.on(events.NewMessage(chats='tradingnava'))
async def my_event_handler(event):
    texte = (event.text)
    texte = texte.split(" ")
    Marche = texte[1]
    Direction = texte[2]
    i = 0
    while os.path.exists('OIF%s.txt' % i):
        i += 1
        if Direction == 'buy':
            f= open(r'C:\Users\USER\PycharmProjects\rakna2\OIF%s.txt' %i, "w")
            f.write("buy b a")
            f.close()
        if Direction == 'sell':
            f= open(r'C:\Users\USER\PycharmProjects\rakna2\OIF%s.txt" %i, "w")
            f.write("sell b a")
            f.close()

Solution

  • import os
    import re
    
    path = r'C:\\Users\\USER\\PycharmProjects\\rakna2\\'
    client.start()
    @client.on(events.NewMessage(chats='tradingnava'))
    async def my_event_handler(event):
        texte = (event.text)
        texte = texte.split(" ")
        Marche = texte[1]
        Direction = texte[2]
    
        allfile = [int(re.findall(f'\d+', fname)[0]) for fname in os.listdir(path) 
                   if fname.startswith("OIF") and re.findall(f'\d+', fname)]
        try:
            s = str(max(allfile) + 1)
        except ValueError:
            allfile = [0]
        
        with open(r'OIF%s.txt' %str(max(allfile) + 1), 'w') as f:
            Direction = 'buy'
            if Direction == 'buy':
                f.write("buy b a")
                f.close()
            elif Direction == 'sell':
                f.write("sell b a")
                f.close()
            else:
                f.write(f"Direction Error {Direction}")
                f.close()