I have the following Python script inside a directory called ‘test’ on my Linux desktop:
#!/usr/bin/python
f = open('test.txt','w')
f.write('testing the script')
So it’s /Home/Desktop/test/script.py
If I go inside the directory and type ./script.py it works fine and creates the test.txt file.
However for some reason I am not able to run the script from the Desktop (/Home/Desktop). I tried ./test/script.py, for instance, but didn’t work.
The file permissions on the script are 755, and on the directory 777.
Any help would be appreciated.
You can use
os.path.dirname()and__file__to get absolute paths like this:This way the script will work on files placed only in the same directory as the script, regardless of the place from which you execute it.