pythonubuntudiscord.pyvirtual-server

Running Python bot on Ubuntu (file or directory not found?)


I run a discord.py bot on my windows machine but I can't run the same bot on Ubuntu. I get a "file not found error" for this line, which is one of the earliest in the bot:

storm = json.load(open(r'jsons\storms.json', 'r'))['wind']

But it does exist. Here is the traceback:

File "/root/bot/utility.py", line 6, in <module>
  storm = json.load(open(r'jsons\storms.json', 'r'))['wind']
FileNotFoundError: [Errno 2] No such file or directory: 'jsons\\storms.json'

The bot works on my Windows machine so I'm assuming there is some difference in Ubuntu or something, since I have copied the full bot and all files onto the Ubuntu system.


Solution

  • You are using the hard-coded Windows route with backslash \, in Unix/Linux is slash /.

    You can access to the right separator with os.path.sep, it will return \ on Windows and / elsewhere.

    But the portable way would be using the join function from os.path, like this:

    import os
    
    storms_path = os.path.join('jsons', 'storms.json')
    storm = json.load(open(storms_path, 'r'))['wind']
    

    This will format your paths using the correct separator and will avoid a number of gotchas you could face building your own.

    os.path docs here