简体   繁体   English

Python - 如果脚本从另一个目录运行,则找不到文件路径

[英]Python - File Path not found if script run from another directory

I'm trying to run a script that works without issue when I run using in console, but causes issue if I try to run it from another directory (via IPython %run <script.py>)我正在尝试运行一个在控制台中运行时没有问题的脚本,但是如果我尝试从另一个目录运行它会导致问题(通过 IPython %run <script.py>)

The issue comes from this line, where it references a folder called "Pickles".问题来自这一行,它引用了一个名为“Pickles”的文件夹。

 with open('Pickles/'+name+'_'+date.strftime('%y-%b-%d'),'rb') as f:
            obj = pickle.load(f)

In Console:在控制台中:

python script.py <---works! python script.py <---有效!

In running IPython (Jupyter) in another folder, it causes a FileNotFound exception.在另一个文件夹中运行 IPython (Jupyter) 时,会导致FileNotFound异常。

How can I make any path references within my scripts more robust, without putting the whole extended path?如何在不放置整个扩展路径的情况下使脚本中的任何路径引用更加健壮?

Thanks in advance!提前致谢!

Since running in the console the way you show works, the Pickles directory must be in the same directory as the script.由于在控制台中以您显示的方式运行,因此Pickles目录必须与脚本位于同一目录中。 You can make use of this fact so that you don't have to hard code the location of the Pickles directory, but also don't have to worry about setting the "current working directory" to be the directory containing Pickles , which is what your current code requires you to do.您可以利用这一事实,这样您就不必对Pickles目录的位置进行硬编码,也不必担心将“当前工作目录”设置为包含Pickles的目录,这就是您当前的代码要求您这样做。

Here's how to make your code work no matter where you run it from:无论您从哪里运行代码,以下是如何使您的代码正常工作:

with open(os.path.join(os.path.dirname(__file__), 'Pickles', name + '_' + date.strftime('%y-%b-%d')), 'rb') as f:
    obj = pickle.load(f)

os.path.dirname(__file__) provides the path to the directory containing the script that is currently running. os.path.dirname(__file__)提供包含当前正在运行的脚本的目录的路径。

Generally speaking, it's a good practice to always fully specify the locations of things you interact with in the filesystem.一般来说,始终完全指定您在文件系统中与之交互的事物的位置是一种很好的做法。 A common way to do this as shown here.执行此操作的常用方法,如此处所示。

UPDATE: I updated my answer to be more correct by not assuming a specific path separator character.更新:我通过不假设特定的路径分隔符来更新我的答案以使其更正确。 I had chosen to use '/' only because the original code in the question already did this.我选择使用“/”只是因为问题中的原始代码已经这样做了。 It is also the case that the code given in the original question, and the code I gave originally, will work fine on Windows.原始问题中给出的代码和我最初给出的代码也可以在 Windows 上正常工作。 The open() function will accept either type of path separator and will do the right thing on Windows. open() function 将接受任一类型的路径分隔符,并将在 Windows 上执行正确的操作。

You have to use absolute paths.您必须使用绝对路径。 Also to be cross platform use join :也可以跨平台使用join

  • First get the path of your script using the variable __file__首先使用变量__file__获取脚本的路径
  • Get the directory of this file with os.path.dirname(__file__)使用os.path.dirname(__file__)获取此文件的目录
  • Get your relative path with os.path.join(os.path.dirname(__file__), "Pickles", f"{name}_{date.strftime('%y-%b-%d')}")使用os.path.join(os.path.dirname(__file__), "Pickles", f"{name}_{date.strftime('%y-%b-%d')}")获取您的相对路径

it gives you:它给你:

with open(os.path.join(os.path.dirname(__file__), "Pickles", f"{name}_{date.strftime('%y-%b-%d')}"), 'rb') as f:
    obj = pickle.load(f)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM