python - 无法使用 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'
解决方案
如果指定目录之一不存在,您将收到此类错误。在这种情况下,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/
?
推荐阅读
- java - 运行项目后无法在intellij中打开静态页面(spring mvc)
- java - java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“”
- java - 单击片段内回收视图中的按钮时显示自定义对话框片段
- gmail - 防病毒软件正在阻止 nodemailer - 错误:证书链中的自签名证书
- arduino - 我真的搞砸了!我需要撤消一些笨拙的脚本
- apache-spark - Spark,如何打印查询?
- python - 无法弄清楚如何让 BS4 检索 /videos 页面上的 youtube 观看次数
- python - groupby pandas python的自定义排序功能
- javascript - 为什么我输入大写方法后空格键不起作用?
- sql-server - 如何创建索引以加快数据检索