在另一个目录中打开文件 (Python)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32470543/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Open File in Another Directory (Python)
提问by dbishop
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:
我一直对 Python 中的目录遍历主题感到困惑,并且有一种我很好奇的情况:我有一个文件,我想在一个与我当前所在的目录基本平行的目录中访问该文件。鉴于此目录结构:
\parentDirectory
\subfldr1
-testfile.txt
\subfldr2
-fileOpener.py
I'm trying to script in fileOpener.py to get out of subfldr2, get into subfldr1, and then call an open() on testfile.txt.
我正在尝试在 fileOpener.py 中编写脚本以退出 subfldr2,进入 subfldr1,然后在 testfile.txt 上调用 open()。
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.
通过浏览 stackoverflow,我看到人们使用os
并os.path
完成此操作,但我只找到了有关脚本源下子目录中文件的示例。
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.
在处理这个问题时,我意识到我可以将脚本重新定位到 subfldr1 中,然后一切都会好起来的,但我对如何完成这件事感到好奇。
EDIT: This question pertains particularly to a Windows machine, as I don't know how drive letters and backslashes would factor into this.
编辑:这个问题特别与 Windows 机器有关,因为我不知道驱动器号和反斜杠会如何影响这个问题。
采纳答案by Jared Mackey
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)
Edit:
编辑:
Here is a way to do it relatively instead of absolute. Not sure if this works on windows, you will have to test it.
这是一种相对而不是绝对的方法。不确定这是否适用于 Windows,您将不得不对其进行测试。
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)
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.
编辑 2:关于 的一个快速说明__file__
,这在交互式解释器中不起作用,因为它是交互式运行的,而不是从实际文件中运行的。
回答by 9953-div-37
import os
import os.path
import shutil
You find your current directory:
您找到当前目录:
d = os.getcwd() #Gets the current working directory
Then you change one directory up:
然后你改变一个目录:
os.chdir("..") #Go up one directory from working directory
Then you can get a tupple/list of all the directories, for one directory up:
然后你可以获得所有目录的元组/列表,对于一个目录:
o = [os.path.join(d,o) for o in os.listdir(d) if os.path.isdir(os.path.join(d,o))] # Gets all directories in the folder as a tuple
Then you can search the tuple for the directory you want and open the file in that directory:
然后你可以在元组中搜索你想要的目录并打开该目录中的文件:
for item in o:
if os.path.exists(item + '\testfile.txt'):
file = item + '\testfile.txt'
Then you can do stuf with the full file path 'file'
然后你可以用完整的文件路径'file'来做stuf
回答by SaretMagnoslove
from pathlib import Path
data_folder = Path("source_data/text_files/")
file_to_open = data_folder / "raw_data.txt"
f = open(file_to_open)
print(f.read())
回答by raman
Its a very old question but I think it will help newbies line me who are learning python. If you have Python 3.4 or above, the pathlib library comes with the default distribution.
这是一个非常古老的问题,但我认为它会帮助我学习 python 的新手。如果您有 Python 3.4 或更高版本,则 pathlib 库随附默认发行版。
To use it, you just pass a path or filename into a new Path() object using forward slashes and it handles the rest. To indicate that the path is a raw string, put r
in front of the string with your actual path.
要使用它,您只需使用正斜杠将路径或文件名传递到新的 Path() 对象中,然后它会处理其余部分。要指示路径是原始字符串,请将r
实际路径放在字符串前面。
For example,
例如,
from pathlib import Path
dataFolder = Path(r'D:\Desktop dump\example.txt')
Source: The easy way to deal with file paths on Windows, Mac and Linux
来源:在 Windows、Mac 和 Linux 上处理文件路径的简单方法
(unicode 错误)“unicodeescape”编解码器无法解码位置 2-3 中的字节:截断的 \UXXXXXXXX 转义