python interpretation of / and windows and ubuntu
Clash Royale CLAN TAG#URR8PPP
python interpretation of / and windows and ubuntu
I have depeloped a flask application that displays information on charts.
I have then deployed the application on:
I then try to execute the application but for some reason I get errors on ubuntu that I did not get on windows. One of these errors is regarding the access to files.
FileNotFoundError: [Errno 2] No such file or directory: '/home/myuser/projects/myflaskappe/mod_on/queries\prices.sql'
I access that file and it is there, the user has permission to access it.
Then I decide to modify the python code that refers to that document:
# original code
data_objects = 'prices':
'sql-path': r'queriesprices.sql',
'source': 'my_db',
'flavor': 'mysql'
I have found that if I modify the code from to
/
then it works perfectly.
/
# modified code
data_objects = 'prices':
'sql-path': r'queries/prices.sql',
'source': 'my_db',
'flavor': 'mysql'
If you notice, I have only modify for
/
to make it work.
/
Why is the reason for this?
There are some other problems as similar to this one that I can't understand why they happen.
1 Answer
1
The reason is that Windows and *nix use different characters for paths to files. In Windows, it is , and in *nix it is
/
.
/
To make your code cross-platform compatible, you should consider using os.path.join()
. For example:
os.path.join()
import os
print(os.path.join("queries", "prices.sql"))
This will give you "queries/prices.sql" on *nix, and "queriesprices.sql" on Windows.
Pretty sure Windows will also accept forward slashes in most cases (not on the command line, though, because it clashes with their options).
– L3viathan
Aug 10 at 7:05
@L3viathan Windows might, but I would still recommend
os.path
regardless. It has a semantically descriptive name, is a widely tested library function, and if in the future the code is to be ported to some obscure OS with weird path names, it can still be extended easily.– ace
Aug 10 at 7:10
os.path
I am in the process of deploying it with the changes but seems like it is the solution.
– jalazbe
Aug 10 at 7:35
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Related: Difference between forward slash (/) and backslash () in file path
– Aran-Fey
Aug 10 at 7:05