Python os模块以相对路径打开当前目录上的文件 [英] Python os module open file above current directory with relative path

查看:2675
本文介绍了Python os模块以相对路径打开当前目录上的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

操作系统模块的文档似乎没有关于如何打开不在子目录中的文件或没有完整路径的脚本运行的当前目录的信息。我的目录结构如下所示。

  /home/matt/project/dir1/cgi-bin/script.py 
/home/matt/project/fileIwantToOpen.txt

open(../../ fileIwantToOpen.txt,r)
pre>

给出文件未找到错误。但是,如果我在cgi-bin目录中启动一个python解释器,并尝试 open(../../ fileIwantToOpen.txt,r)出于明显的可移植性原因,我不想在完整路径中进行硬编码。是否在OS模块中有一组方法可以执行此操作?

解决方案

打开应该是相对于当前的工作目录,你从中运行脚本的目录。所以上面的例子只有在你从cgi-bin目录运行的时候才能工作。



一个简单的解决方案是让你的路径和脚本相关。一个可能的解决方案。

$ p $ import os.path

basepath = os.path.dirname(__ file__)
filepath = os.path.abspath(os.path.join(basepath,..,..,fileIwantToOpen.txt))
f = open(filepath,r)

通过这种方式,您将获得正在运行的脚本的路径(basepath)与您要打开的文件的相对路径。 os.path 将负责连接两条路径的细节。


The documentation for the OS module does not seem to have information about how to open a file that is not in a subdirectory or the current directory that the script is running in without a full path. My directory structure looks like this.

/home/matt/project/dir1/cgi-bin/script.py
/home/matt/project/fileIwantToOpen.txt

open("../../fileIwantToOpen.txt","r")

Gives a file not found error. But if I start up a python interpreter in the cgi-bin directory and try open("../../fileIwantToOpen.txt","r") it works. I don't want to hard code in the full path for obvious portability reasons. Is there a set of methods in the OS module that CAN do this?

解决方案

The path given to open should be relative to the current working directory, the directory from which you run the script. So the above example will only work if you run it from the cgi-bin directory.

A simple solution would be to make your path relative to the script. One possible solution.

import os.path

basepath = os.path.dirname(__file__)
filepath = os.path.abspath(os.path.join(basepath, "..", "..", "fileIwantToOpen.txt"))
f = open(filepath, "r")

This way you'll get the path of the script you're running (basepath) and join that with the relative path of the file you want to open. os.path will take care of the details of joining the two paths.

这篇关于Python os模块以相对路径打开当前目录上的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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