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

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

问题描述

假设python代码在以前的Windows目录中被称为main,并且运行时安装代码的地方需要访问目录main / 2091 / data.txt。

Suppose python code is executed in not known by prior windows directory say 'main' , and wherever code is installed when it runs it needs to access to directory 'main/2091/data.txt' .

我应该如何使用open(location)功能?什么应该是位置?

how should I use open(location) function? what should be location ?

编辑:

我发现以下简单的代码将工作。任何缺点?

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+');


推荐答案

使用这种类型的东西你需要小心些你的实际工作目录是。例如,您不能从文件所在的目录运行脚本。在这种情况下,您不能仅使用相对路径。

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.

所以你可以用这个:

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天全站免登陆