Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running a Python Script Inside Another Directory

Tags:

python

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.

like image 404
Daniel Scocco Avatar asked Oct 08 '12 23:10

Daniel Scocco


People also ask

Can I run Python from any directory?

To be able to run the script, no matter what directory you are in: move the script into a directory listed inside the $PATH environment variable, like /usr/local/bin , or make a directory ad-hoc for your scripts and add that dir to the PATH variable.

How do I go to a specific directory in Python?

To find the current working directory in Python, use os. getcwd() , and to change the current working directory, use os. chdir(path) .

How do I run a .py file in CMD?

To run Python scripts with the python command, you need to open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this: $ python3 hello.py Hello World! If everything works okay, after you press Enter , you'll see the phrase Hello World!


2 Answers

You can use os.path.dirname() and __file__ to get absolute paths like this:

#!/usr/bin/python

import os  # We need this module

# Get path of the current dir, then use it to create paths:
CURRENT_DIR = os.path.dirname(__file__)
file_path = os.path.join(CURRENT_DIR, 'test.txt')

# Then work using the absolute paths:
f = open(file_path,'w')
f.write('testing the script')

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.

like image 148
Tadeck Avatar answered Oct 14 '22 08:10

Tadeck


In your open('test.txt', 'w') put open(r'./test.txt', 'w'). When you run it, use "python script.py. See if that works.

like image 22
alvonellos Avatar answered Oct 14 '22 09:10

alvonellos