1

I'm designing a Discord bot using discord.py and need to store user information in files. The issue I'm worried about is that if two commands are executed simultaneously, that the bot will attempt to access the same user's information file from two scripts at once. Is there a really simple way I can lock down file access? I've tried using Google but it hasn't really gotten me anywhere so I'm trying this.

Thanks in advance!

Village
  • 13
  • 2
  • 3
    You will probably need to bite the bullet and switch to a more suitable database than just files. – chluebi Jan 25 '21 at 19:09
  • 2
    Does this answer your question? [Locking a file in Python](https://stackoverflow.com/questions/489861/locking-a-file-in-python) – oskros Jan 25 '21 at 19:12

1 Answers1

2

You are describing a condition called race condition, and it has a lot of different ways to combat, but I think the best way is to use os.O_NONBLOCK.

import os
with open('/path/to/file', 'a', os.O_NONBLOCK) as f:
    f.write('text')
    f.flush()

See this answer for more information

In general, I think that it would be best to use a "real" database (such as SQLite or mongo) that already has built-in solutions for this problem

ZeroKnight
  • 518
  • 3
  • 17
TheZadok42
  • 147
  • 1
  • 9