如何可靠地打开与当前运行的脚本同一目录中的文件
我曾经通过简单地使用以下命令来打开与当前运行的 Python 脚本位于同一目录中的文件:
open("Some file.txt", "r")
但是,我发现当脚本在 Windows 中双击运行时,它会尝试从以下位置打开文件:错误的目录。
我都会使用以下形式的命令
open(os.path.join(sys.path[0], "Some file.txt"), "r")
从那时起,每当我想打开文件时, 。这适用于我的特定用法,但我不确定 sys.path[0] 在其他用例中是否会失败。
所以我的问题是:打开与当前运行的 Python 脚本位于同一目录中的文件的最佳和最可靠的方法是什么?
到目前为止,这是我能够弄清楚的:
os.getcwd()
和os.path.abspath('')
返回“当前工作目录”,而不是脚本目录。os.path.dirname(sys.argv[0])
和os.path.dirname(__file__)
返回用于调用脚本的路径,该路径可能是相对的甚至是空白的(如果脚本位于 cwd 中)。此外,当脚本在 IDLE 或 PythonWin 中运行时,__file__
不存在。sys.path[0]
和os.path.abspath(os.path.dirname(sys.argv[0]))
似乎返回脚本目录。我不确定这两者之间是否有任何区别。
编辑:
我刚刚意识到我想要做的事情最好描述为“在与包含模块相同的目录中打开文件”。换句话说,如果我导入我编写的位于另一个目录中的模块,并且该模块打开一个文件,我希望它在模块的目录中查找该文件。我认为我发现的任何东西都无法做到这一点......
I used to open files that were in the same directory as the currently running Python script by simply using a command like:
open("Some file.txt", "r")
However, I discovered that when the script was run in Windows by double-clicking it, it would try to open the file from the wrong directory.
Since then I've used a command of the form
open(os.path.join(sys.path[0], "Some file.txt"), "r")
whenever I wanted to open a file. This works for my particular usage, but I'm not sure if sys.path[0]
might fail in some other use case.
So my question is: What is the best and most reliable way to open a file that's in the same directory as the currently running Python script?
Here's what I've been able to figure out so far:
os.getcwd()
andos.path.abspath('')
return the "current working directory", not the script directory.os.path.dirname(sys.argv[0])
andos.path.dirname(__file__)
return the path used to call the script, which may be relative or even blank (if the script is in the cwd). Also,__file__
does not exist when the script is run in IDLE or PythonWin.sys.path[0]
andos.path.abspath(os.path.dirname(sys.argv[0]))
seem to return the script directory. I'm not sure if there's any difference between these two.
Edit:
I just realized that what I want to do would be better described as "open a file in the same directory as the containing module". In other words, if I import a module I wrote that's in another directory, and that module opens a file, I want it to look for the file in the module's directory. I don't think anything I've found is able to do that...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
我总是使用:
join()
调用预先考虑当前工作目录,但文档说如果某个路径是绝对路径,则其左侧的所有其他路径都会被删除。因此,当dirname(__file__)
返回绝对路径时,getcwd()
将被删除。此外,
realpath
调用会解析符号链接(如果找到)。这可以避免在 Linux 系统上使用 setuptools 进行部署时出现的麻烦(脚本符号链接到/usr/bin/
——至少在 Debian 上)。您可以使用以下命令打开同一文件夹中的文件:
我使用它来将资源与 Windows 和 Linux 上的多个 Django 应用程序捆绑在一起,它的工作方式就像一个魅力!
I always use:
The
join()
call prepends the current working directory, but the documentation says that if some path is absolute, all other paths left of it are dropped. Therefore,getcwd()
is dropped whendirname(__file__)
returns an absolute path.Also, the
realpath
call resolves symbolic links if any are found. This avoids troubles when deploying with setuptools on Linux systems (scripts are symlinked to/usr/bin/
-- at least on Debian).You may the use the following to open up files in the same folder:
I use this to bundle resources with several Django application on both Windows and Linux and it works like a charm!
在 Python 3.4 上,添加了
pathlib
模块,并且以下代码将可靠地打开与当前脚本相同的目录中的文件:如果您需要将文件路径作为字符串用于某些类似
open
的 API,则可以使用获取它Absolute()
:注意:Python
REPL
,例如在没有目标或ipythonpython
命令code> 不要公开__file__
。On Python 3.4, the
pathlib
module was added, and the following code will reliably open a file in the same directory as the current script:If you instead need the file path as a string for some
open
-like API, you can get it usingabsolute()
:NOTE: Python
REPL
s such as running thepython
command without a target oripython
do not expose__file__
.引用Python文档:
如果您从终端运行脚本,则
sys.path[0]
就是您要查找的内容。但是,如果您有:
那么请注意!
To quote from the Python documentation:
If you are running the script from the terminal,
sys.path[0]
is what you are looking for.However, if you have:
So watch out!
好的,这就是我所做的
sys.argv 始终是您在终端中输入的内容或在使用 python.exe 或 pythonw.exe 执行时用作文件路径的内容
例如,您可以通过多种方式运行文件 text.py,它们各自给出你有一个不同的答案,他们总是给你输入 python 的路径。
好吧,知道你可以获取文件名,很重要,现在要获取你可以知道的应用程序目录,请使用 os.path,特别是abspath 和 dirname
这将输出这个:
无论你是否输入 python test,它总是会输出这个。 py 或 python "C:\Documents and Settings\Admin\test.py"
使用 __file__ 的问题
考虑这两个文件
test.py
import_test.py
“python test.py”的输出
“python test_import.py”的输出
因此,正如您所看到的 file 始终为您提供正在运行的 python 文件,其中 sys .argv[0] 为您提供始终从解释器运行的文件。根据您的需求,您需要选择最适合您需求的一种。
Ok here is what I do
sys.argv is always what you type into the terminal or use as the file path when executing it with python.exe or pythonw.exe
For example you can run the file text.py several ways, they each give you a different answer they always give you the path that python was typed.
Ok so know you can get the file name, great big deal, now to get the application directory you can know use os.path, specifically abspath and dirname
That will output this:
it will always output this no matter if you type python test.py or python "C:\Documents and Settings\Admin\test.py"
The problem with using __file__
Consider these two files
test.py
import_test.py
Output of "python test.py"
Output of "python test_import.py"
So as you can see file gives you always the python file it is being run from, where as sys.argv[0] gives you the file that you ran from the interpreter always. Depending on your needs you will need to choose which one best fits your needs.
我常用的有以下几种。它适用于测试,也可能适用于其他用例。
with open(os.path.join(os.path.dirname(__file__), 'some_file.txt'), 'r') as f:
这个答案在 https://stackoverflow.com/questions/ 10174211/如何制作始终相对于当前模块文件路径
I commonly use the following. It works for testing and probably other use cases as well.
with open(os.path.join(os.path.dirname(__file__), 'some_file.txt'), 'r') as f:
This answer is recommended in https://stackoverflow.com/questions/10174211/how-to-make-an-always-relative-to-current-module-file-path
您可以尝试这种简单的方法吗:
Can you try this simple approach just like this:
因为我在尝试使用 emacs 中的
__file__
或sys.argv[0]
时遇到错误,所以我这样做了:Because I get an error trying to use
__file__
orsys.argv[0]
from emacs I do it that way:尝试了所有这些解决方案后,我仍然遇到了不同的问题。所以我发现最简单的方法是创建一个 python 文件:config.py,其中包含一个包含文件绝对路径的字典并将其导入到脚本中。
类似于
config.py 内部的内容:
它不是自动的,但当您必须在不同的目录或不同的计算机中工作时,它是一个很好的解决方案。
After trying all of this solutions, I still had different problems. So what I found the simplest way was to create a python file: config.py, with a dictionary containing the file's absolute path and import it into the script.
something like
where config.py has inside:
It is not automatic but it is a good solution when you have to work in different directory or different machines.
我会这样做:
上面的代码使用 abspath 相当于使用
normpath(join(os.getcwd(), path))
[来自 pydocs]。然后它检查该文件是否确实存在,然后使用上下文管理器来打开它,这样您就不必记住在文件句柄上调用关闭。恕我直言,从长远来看,这样做会给你省去很多痛苦。I'd do it this way:
The above code builds an absolute path to the file using abspath and is equivalent to using
normpath(join(os.getcwd(), path))
[that's from the pydocs]. It then checks if that file actually exists and then uses a context manager to open it so you don't have to remember to call close on the file handle. IMHO, doing it this way will save you a lot of pain in the long run.