3

My Python script works perfectly if I execute it directly from the directory it's located in. However if I back out of that directory and try to execute it from somewhere else (without changing any code or file locations), all the relative paths break and I get a FileNotFoundError.

The script is located at ./scripts/bin/my_script.py. There is a directory called ./scripts/bin/data/. Like I said, it works absolutely perfectly as long as I execute it from the same directory... so I'm very confused.

Successful Execution (in ./scripts/bin/): python my_script.py

Failed Execution (in ./scripts/): Both python bin/my_script.py and python ./bin/my_script.py

Failure Message:

Traceback (most recent call last):
  File "./bin/my_script.py", line 87, in <module>
    run()
  File "./bin/my_script.py", line 61, in run
    load_data()
  File "C:\Users\XXXX\Desktop\scripts\bin\tables.py", line 12, in load_data
DATA = read_file("data/my_data.txt")
  File "C:\Users\XXXX\Desktop\scripts\bin\fileutil.py", line 5, in read_file
    with open(filename, "r") as file:
FileNotFoundError: [Errno 2] No such file or directory: 'data/my_data.txt'

Relevant Python Code:

def read_file(filename):
    with open(filename, "r") as file:
        lines = [line.strip() for line in file]
        return [line for line in lines if len(line) == 0 or line[0] != "#"]

def load_data():
    global DATA
    DATA = read_file("data/my_data.txt")
4

2 回答 2

6

是的,这是合乎逻辑的。这些文件与您的工作目录相关。您可以通过从不同的目录运行脚本来更改它。您可以做的是获取您在运行时运行的脚本的目录并从中构建。

import os

def read_file(filename):
    #get the directory of the current running script. "__file__" is its full path
    path, fl = os.path.split(os.path.realpath(__file__))
    #use path to create the fully classified path to your data
    full_path = os.path.join(path, filename)
    with open(full_path, "r") as file:
       #etc
于 2013-08-29T23:14:08.297 回答
2

您的资源文件与您的脚本相关。这没关系,但你需要使用

os.path.realpath(__file__)

或者

os.path.dirname(sys.argv[0])

获取脚本所在的目录。然后使用os.path.join()或其他函数生成资源文件的路径。

于 2013-08-29T23:37:20.967 回答