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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top