我正在尝试使用Python创建和写入文本文件.我搜索过,无法找到此错误的解决方案/原因.
这是不起作用的代码:
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' #
Run Code Online (Sandbox Code Playgroud)
我找到的大多数答案都与路径中的斜线有关,所以......
I tried 'D:/temp/test.txt' and got an error.
I tried r'D:\temp\test.txt' and got an error.
Run Code Online (Sandbox Code Playgroud)
当我尝试在D的根目录创建文件时:/我已成功.
'D:/test.txt' works.
'D:\\test.txt' works.
r'D:\test.txt' works.
Run Code Online (Sandbox Code Playgroud)
在尝试创建文件时,似乎无法创建我想要的目录路径.在Windows上使用Python在特定路径上创建文件的正确方法是什么(7)?我误解open()可以做什么?如果它们不存在,它是否会创建目录,或者在"写入"模式下使用open()创建文件之前是否需要显式创建目录路径?