我正在尝试学习python中的文件I / O,我正在尝试按照以下代码在计算机的D驱动器中生成一个文本文件,其中包含代码中编写的语句,但是编译失败,文件“我想要创建”是不可用的,这是显而易见的。那么如何创建文件?
file = open(r'D:/pyflie/text.txt',"w")
file.write("Hello World")
file.write("This is our new text file")
file.write("and this is another line.")
file.write("Why? Because we can.")
file.close()
,显示的错误是
C:\Users\ssgu>python D:/pyfile/fw.py
Traceback (most recent call last):
File "D:/pyfile/fw.py", line 1, in <module>
file = open(r'D:/pyflie/text.txt',"w")
FileNotFoundError: [Errno 2] No such file or directory:
'D:/pyflie/text.txt'
答案 0 :(得分:2)
如果指定的目录之一不存在,则会出现此类错误。在这种情况下,D:/pyflie/
还不存在,因此必须事先创建。然后,您的代码应正常创建并打开文件。您可以预先检查:
import os
if not os.path.exists(r"D:\pyflie"):
os.makedirs(r"D:\pyflie")
file = open(r'D:\pyflie\text.txt',"w")
file.write("Hello World")
file.write("This is our new text file")
file.write("and this is another line.")
file.write("Why? Because we can.")
file.close()
此外,请检查路径名中是否有错字。您是说D:/pyfile/
吗?