How can I have Python look for files in the location of the program?
-
28-10-2019 - |
سؤال
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?
المحلول
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')
نصائح أخرى
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
لا تنتمي إلى StackOverflow