在另一个目录中打开文件 (Python) [英] Open File in Another Directory (Python)

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

问题描述

我一直对 Python 中的目录遍历主题感到困惑,并且有一种我很好奇的情况:我有一个文件,我想在一个与我访问的目录基本平行的目录中访问它当前在.鉴于此目录结构:

I've always been sort of confused on the subject of directory traversal in Python, and have a situation I'm curious about: I have a file that I want to access in a directory essentially parallel to the one I'm currently in. Given this directory structure:

\parentDirectory
    \subfldr1
        -testfile.txt
    \subfldr2
        -fileOpener.py

我正在尝试在 fileOpener.py 中编写脚本以退出 subfldr2,进入 subfldr1,然后在 testfile.txt 上调用 open().

I'm trying to script in fileOpener.py to get out of subfldr2, get into subfldr1, and then call an open() on testfile.txt.

通过浏览 stackoverflow,我看到人们使用 osos.path 来完成此操作,但我只找到了有关脚本下子目录中文件的示例起源.

From browsing stackoverflow, I've seen people use os and os.path to accomplish this, but I've only found examples regarding files in subdirectories beneath the script's origin.

为此,我意识到我可以将脚本重新定位到 subfldr1 中,然后一切都会好起来的,但我对如何实现这一点感到好奇.

Working on this, I realized I could just relocate the script into subfldr1 and then all would be well, but my curiosity is piqued as to how this would be accomplished.

这个问题特别与 Windows 机器有关,因为我不知道驱动器号和反斜杠会如何影响这个.

This question pertains particularly to a Windows machine, as I don't know how drive letters and backslashes would factor into this.

推荐答案

如果您知道文件的完整路径,您可以执行类似的操作.但是,如果您的问题与相对路径直接相关,那么我不熟悉并且必须进行研究和测试.

If you know the full path to the file you can just do something similar to this. However if you question directly relates to relative paths, that I am unfamiliar with and would have to research and test.

path = 'C:\\Users\\Username\\Path\\To\\File'

with open(path, 'w') as f:
    f.write(data)

这是一种相对而不是绝对的方法.不确定这是否适用于 Windows,您必须对其进行测试.

Here is a way to do it relatively instead of absolute. Not sure if this works on windows, you will have to test it.

import os

cur_path = os.path.dirname(__file__)

new_path = os.path.relpath('..\\subfldr1\\testfile.txt', cur_path)
with open(new_path, 'w') as f:
    f.write(data)

编辑 2: 关于 __file__ 的一个快速说明,这在交互式解释器中不起作用,因为它是交互式运行的,而不是从实际文件中运行的.

Edit 2: One quick note about __file__, this will not work in the interactive interpreter due it being ran interactively and not from an actual file.

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

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