在 Python 中的相对位置打开文件 [英] Open file in a relative location in Python

查看:31
本文介绍了在 Python 中的相对位置打开文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我的python代码在一个名为main的目录下执行,应用程序需要访问main/2091/data.txt.

Suppose my python code is executed a directory called main and the application needs to access main/2091/data.txt.

我应该如何使用open(location)?参数 location 应该是什么?

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 = "2091sample.txt"
path = os.getcwd()+file
fp = open(path, 'r+');

推荐答案

对于这种类型的事情,你需要小心你的实际工作目录是什么.例如,您可能无法从文件所在的目录运行脚本.在这种情况下,您不能仅使用相对路径本身.

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.

如果您确定您想要的文件位于脚本实际所在的子目录下,您可以使用 __file__ 来帮助您.__file__ 是您正在运行的脚本所在位置的完整路径.

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:

import os
script_dir = os.path.dirname(__file__) #<-- absolute dir the script is in
rel_path = "2091/data.txt"
abs_file_path = os.path.join(script_dir, rel_path)

这篇关于在 Python 中的相对位置打开文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆