在 Python 中的相对位置打开文件
假设我的 python 代码在名为 main
的目录中执行,并且应用程序需要访问 main/2091/data.txt
。
我应该如何使用open(location)
?参数location
应该是什么?
我发现下面的简单代码可以工作..它有什么缺点吗?
file = "\2091\sample.txt"
path = os.getcwd()+file
fp = open(path, 'r+');
Suppose my python code is executed a directory called main
and the application needs to access main/2091/data.txt
.
how should I use open(location)
? what should the parameter location
be?
I found that below simple code will work.. does it have any disadvantages?
file = "\2091\sample.txt"
path = os.getcwd()+file
fp = open(path, 'r+');
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(14)
对于这种类型的事情,您需要小心您的实际工作目录是什么。例如,您可能无法从文件所在的目录运行脚本。在这种情况下,您不能仅使用相对路径本身。
如果您确定所需的文件位于脚本实际所在的子目录中,则可以使用 __file__ 来帮助您。
__file__
是您正在运行的脚本所在位置的完整路径。所以你可以摆弄这样的事情:
With this type of thing you need to be careful what your actual working directory is. For example, you may not run the script from the directory the file is in. In this case, you can't just use a relative path by itself.
If you are sure the file you want is in a subdirectory beneath where the script is actually located, you can use
__file__
to help you out here.__file__
is the full path to where the script you are running is located.So you can fiddle with something like this:
这段代码工作正常:
This code works fine:
我创建了一个帐户,只是为了澄清我认为在 Russ 最初的回复中发现的差异。
作为参考,他最初的答案是:
这是一个很好的答案,因为它试图动态创建所需文件的绝对系统路径。
Cory Mawhorter 注意到 __file__ 是一个相对路径(在我的系统上也是如此),并建议使用 os.path.abspath(__file__) 。然而,os.path.abspath返回当前脚本的绝对路径(即/path/to/dir/foobar.py)
要使用此方法(以及如何我最终让它工作了)你必须从路径末尾删除脚本名称:
生成的abs_file_path(在本例中)变为:
/path/to/dir/2091/data.txt
I created an account just so I could clarify a discrepancy I think I found in Russ's original response.
For reference, his original answer was:
This is a great answer because it is trying to dynamically creates an absolute system path to the desired file.
Cory Mawhorter noticed that
__file__
is a relative path (it is as well on my system) and suggested usingos.path.abspath(__file__)
.os.path.abspath
, however, returns the absolute path of your current script (i.e./path/to/dir/foobar.py
)To use this method (and how I eventually got it working) you have to remove the script name from the end of the path:
The resulting abs_file_path (in this example) becomes:
/path/to/dir/2091/data.txt
这取决于您使用的操作系统。如果您想要一个与 Windows 和 *nix 兼容的解决方案,例如:
应该可以正常工作。
path
模块能够为其运行的任何操作系统格式化路径。另外,只要您拥有正确的权限,Python 就可以很好地处理相对路径。编辑:
正如kindall在评论中提到的,python无论如何都可以在unix风格和windows风格路径之间转换,所以更简单的代码也可以工作:
话虽这么说,
path
模块仍然有一些有用的功能。It depends on what operating system you're using. If you want a solution that is compatible with both Windows and *nix something like:
should work fine.
The
path
module is able to format a path for whatever operating system it's running on. Also, python handles relative paths just fine, so long as you have correct permissions.Edit:
As mentioned by kindall in the comments, python can convert between unix-style and windows-style paths anyway, so even simpler code will work:
That being said, the
path
module still has some useful functions.我花了很多时间来发现为什么我的代码找不到在 Windows 系统上运行 Python 3 的文件。所以我补充道。之前/并且一切正常:
I spend a lot time to discover why my code could not find my file running Python 3 on the Windows system. So I added . before / and everything worked fine:
试试这个:
Python 3.4 引入了一个新的标准库,用于处理文件和路径,称为 pathlib。这对我有用!
Try this:
Python 3.4 introduced a new standard library for dealing with files and paths called pathlib. It works for me!
代码:
说明:
导入库:
使用
__file__
获取当前脚本的路径:将脚本路径分成多项:
删除列表中的最后一项(实际的脚本文件) ):
添加相对文件的路径:
加入列表项,并添加相对路径的文件:
现在您可以对文件执行任何您想要的操作,例如:
Code:
Explanation:
Import library:
Use
__file__
to attain the current script's path:Separates the script path into multiple items:
Remove the last item in the list (the actual script file):
Add the relative file's path:
Join the list items, and addition the relative path's file:
Now you are set to do whatever you want with the file, such as, for example:
获取父文件夹的路径,然后
os.join
您的相关文件到最后。与
pathlib
相同:Get the path of the parent folder, then
os.join
your relative files to the end.The same thing with
pathlib
:如果该文件位于您的父文件夹中,例如。 follower.txt,您只需使用
open('../follower.txt', 'r').read()
If the file is in your parent folder, eg. follower.txt, you can simply use
open('../follower.txt', 'r').read()
Python 只是将您提供的文件名传递给操作系统,然后操作系统打开它。如果您的操作系统支持像
main/2091/data.txt
这样的相对路径(提示:确实如此),那么就可以正常工作。您可能会发现回答此类问题的最简单方法就是尝试一下,看看会发生什么。
Python just passes the filename you give it to the operating system, which opens it. If your operating system supports relative paths like
main/2091/data.txt
(hint: it does), then that will work fine.You may find that the easiest way to answer a question like this is to try it and see what happens.
不确定这是否在所有地方都有效。
我在 ubuntu 中使用 ipython。
如果您想读取当前文件夹子目录中的文件:
您的脚本位于当前文件夹中
只需尝试这个:
Not sure if this work everywhere.
I'm using ipython in ubuntu.
If you want to read file in current folder's sub-directory:
your script is in current-folder
simply try this:
在 Python 3.4 (PEP 428) 中,
pathlib
被引入,允许您以面向对象的方式处理文件时尚:with
关键字也将确保即使出现问题(例如未处理的Exception
、sigint 或类似情况),您的资源也会正确关闭In Python 3.4 (PEP 428) the
pathlib
was introduced, allowing you to work with files in an object oriented fashion:The
with
keyword will also ensure that your resources get closed properly, even if you get something goes wrong (like an unhandledException
, sigint or similar)当我还是一个初学者时,我发现这些描述有点令人生畏。一开始我会尝试
对于 Windows
,这会引发
语法错误
。我曾经经常感到困惑。然后在谷歌上浏览了一下。找到了发生错误的原因。 为初学者编写此内容这是因为要以 Unicode 读取路径,您只需在启动文件路径时添加
\
现在只需添加
\
在启动目录之前。When I was a beginner I found these descriptions a bit intimidating. As at first I would try
For Windows
and this would raise an
syntax error
. I used get confused alot. Then after some surfing across google. found why the error occurred. Writing this for beginnersIt's because for path to be read in Unicode you simple add a
\
when starting file pathAnd now it works just add
\
before starting the directory.