1

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.

Break
  • 332
  • 3
  • 19

3 Answers3

2

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

MGP
  • 2,981
  • 35
  • 34
  • All answers were helpful to me but I can only pick one and yours is the method that I will be using in the future. Thank you – Break Aug 04 '20 at 16:54
  • 1
    The pathlib method mentioned by @Ilu is also good, it was introduced in 3.4 so you may not find many code examples around. Happy coding! – MGP Aug 05 '20 at 10:40
1

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.

piet.t
  • 11,718
  • 21
  • 43
  • 52
Tasnuva Leeya
  • 2,515
  • 1
  • 13
  • 21
1

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']
Ilu
  • 56
  • 4