Daniel Scocco
Daniel Scocco

Reputation: 7266

Running a Python Script Inside Another Directory

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.

Upvotes: 7

Views: 30900

Answers (5)

ernie
ernie

Reputation: 6356

If your cwd is /Desktop/test, and then you try to execute ./test/script.py, you're trying to run a script at /Desktop/test/test/script.py. More likely, you just wanted to do ./script.py.

As an aside, your question would have been more useful if you had provided the error message you got from the command line, rather than just saying "didn't work"

If the script is running and nothing is echoed to the console, most likely it's working. Note that opening a file in 'w' mode truncates the file. Maybe you want to use a+?

Upvotes: 2

Tadeck
Tadeck

Reputation: 137300

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.

Upvotes: 19

dckrooney
dckrooney

Reputation: 3121

What directory are you executing in? You might try using:

import os

print os.getcwd()

to verify that the working directory is what you think it is.

Upvotes: 0

alvonellos
alvonellos

Reputation: 1062

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

Upvotes: 1

tink
tink

Reputation: 15206

"And so on" doesn't meant much.

Where in the file-system are you? What is the test directories relative position to your location?

Have you tried a fully qualified path? E.g.,

/home/daniel/test/script.py

Upvotes: 0

Related Questions