问题描述
我正在尝试使用Python创建并写入文本文件.我已经搜索过,但找不到该错误的解决方案/原因.
I am trying to create and write to a text file using Python. I have searched and cannot find a solution/reason for this error.
这是无效的代码:
afile = 'D:\\temp\\test.txt'
outFile = open(afile, 'w' )
outFile.write('Test.')
outFile.close()
# Error: 2
# Traceback (most recent call last):
# File "<maya console>", line 1, in <module>
# IOError: [Errno 2] No such file or directory: 'D:\\temp\\test.txt' #
我找到的大多数答案都与路径中的斜杠有关,所以...
Most answers I found related to the slashes in the path, so...
I tried 'D:/temp/test.txt' and got an error.
I tried r'D:\temp\test.txt' and got an error.
当我尝试在D的根目录创建文件时:/我成功了.
When I try to create a file at the root of D:/ I have success.
'D:/test.txt' works.
'D:\\test.txt' works.
r'D:\test.txt' works.
似乎在尝试创建文件时无法创建我想要的目录路径.在Windows(7)上使用Python在特定路径下创建文件的正确方法是什么?我是否误解了open()可以做什么?如果目录不存在,它会创建目录吗?还是需要我在写入"模式下使用open()创建文件之前明确创建目录路径?
It seems that I can't create the directory path I would like while trying to create the file. What is the correct method for creating files at a specific path with Python on Windows(7)? Am I misunderstanding what open() can do? Does it create directories if they don't exist or do I need to explicitly create the directory path before I use open() in 'write' mode to create a file?
推荐答案
您正确地认为文件的父目录必须存在才能使open
成功.解决此问题的简单方法是调用 os.makedirs
.
You are correct in surmising that the parent directory for the file must exist in order for open
to succeed. The simple way to deal with this is to make a call to os.makedirs
.
从文档:
递归目录创建功能.与mkdir()
类似,但是使所有中间级目录都包含叶子目录.
Recursive directory creation function. Like mkdir()
, but makes all intermediate-level directories needed to contain the leaf directory.
所以您的代码可能会运行如下代码:
So your code might run something like this:
filename = ...
dirname = os.path.dirname(filename)
if not os.path.exists(dirname):
os.makedirs(dirname)
with open(filename, 'w'):
...
这篇关于尝试使用open(filename,'w')会出现IOError:[Errno 2]如果目录不存在,则没有这样的文件或目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!