I'm having a problem with a program in which I have to load images and pickled objects: my Python software doesn't appear to be looking in the location of the program. I have my program in a folder called "King's Capture," and my images in a folder within "King's Capture" labeled "data." I want to have python find the files no matter where I place the folder "King's Capture." It seems to me that python should already be looking in the folder where the program itself is, but it apparently isn't. How should I go about this?
Asked
Active
Viewed 102 times
2 Answers
1
You can access the path of the current script file via the special variable __file__
. So try this within your main program script:
import os
// ...
data_dir = os.path.join(os.path.dirname(__file__), 'data')

gsteff
- 4,764
- 1
- 20
- 17
1
Try this
import sys, os
ROOT = os.path.dirname(os.path.abspath(__file__))
directory = ROOT + os.path.sep + 'data'
for eachFile in os.listdir(directory):
fileName = directory + os.path.sep + eachFile
print fileName

Aamir Rind
- 38,793
- 23
- 126
- 164
-
Great solution! :) I picked Gsteff's because it was simpler for what I wanted to do, but I must say that your response was quick and effective. :D – user1048917 Feb 19 '12 at 22:42
-
Just one thing: you should use `os.path.join()` instead of appending the separator manually. – danielkza Feb 20 '12 at 08:16