python - 尝试创建文件时出现“文件不存在”错误
问题描述
我正在尝试写入一个不存在的文件。有人告诉我,如果"w"
文件不存在,使用它时会创建该文件。但是,这不起作用并返回了错误。然后我添加了一行"x"
用于创建文件。这仍然返回错误。
这是错误:
Traceback (most recent call last):
File "C:\Users\brain\Documents\Python projects\Calendar\Calendar.py", line 22, in <module>
day = open(today+".txt", "x")
FileNotFoundError: [Errno 2] No such file or directory: '6/11/2021.txt'
这是代码:
print("You do not have any reminders for today.")
print("Would you like to make some?")
newtoday = input().lower()
if newtoday == "yes":
filename = open("filenames.txt", "w")
filename.write(today)
day = open(today+".txt", "x")
day.close()
day = open(today+".txt", "w")
print("What would you like the title of the reminder to be?")
title = input()
print("Add any extra details below e.g. time, place.")
det = input()
day.write(title+": "+det, "(x)")
filename.close()
day.close()
解决方案
由于today
是一个包含/
字符的字符串,day = open(today+".txt", "x")
将读取此字符串作为在其中创建文件的路径。您的today
变量包含6/11/2021
,因此它将查找目录结构6/11
并在该文件夹中尝试创建文件2021.txt
。由于他找不到那些目录,因此指令将失败。您可以尝试格式化您的文件名6-11-2021.txt
。如果您确实想使用目录,可以使用os.mkdirtoday
解析和创建目录
推荐阅读
- javascript - 使用 isInteger 检查字符(作为字符串)是否为数字不起作用
- vb.net - 如何在 VB.Net 的 ListView 中显示图标
- android - Flutter(稳定)运行 Android throwToolExit(包:flutter_tools/src/base/common.dart:14:3)
- mongodb - 流星连接到远程mongodb错误自签名证书
- php - PHP 没有执行 INSERT INTO
- r - 为什么 For 循环在 R 和循环索引中无效
- php - PHP preg_match 语言相关解释错误
- css - CSS绝对定位表格行和单元格宽度与Divs
- javascript - 事件侦听器回调在另一个事件侦听器的回调中设置时立即触发。反应JS
- excel - 如何在 TAB 分隔文件的单元格中嵌入“字体、颜色和字体大小”,就像处理“= TEXT”一样