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

488 Views Asked by At

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.

3

There are 3 best solutions below

2
MGP On BEST ANSWER

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

0
Tasnuva Leeya On

ubuntu uses '/' instead of '\'. so instead of:

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

use :

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

it should work.

0
Ilu On

Instead of hardcoding either windows or linux style paths, you may want to switch to a more robust implementation using the pathlib standard library by python: https://docs.python.org/3/library/pathlib.html

A minimum example would look like this:

from pathlib import Path
folder = Path("add/path/to/file/here/")
path_to_file = folder / "some_random_file.xyz"
f = open(path_to_file)

Notice how you can easily use the / operator once you have initialized a Path object, to append e.g. the filename.

In your case for the json file:

import json
from pathlib import Path
folder = Path("jsons/")
path_to_file = folder / "storms.json"
storm = json.load(open(path_to_file, 'r'))['wind']