首页 > 解决方案 > 无法使用 python 创建文本文件

问题描述

我正在尝试在 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' 

标签: pythonpython-3.x

解决方案


如果指定目录之一不存在,您将收到此类错误。在这种情况下,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/


推荐阅读