You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python跨目录创建文件报错及多方式创建/追加文件咨询

问题解决与示例

错误原因分析

你的报错源于两个核心问题:

  • 输入的日期包含/,这是操作系统的路径分隔符,Python会将../SU/2023/01/01.txt解析为嵌套路径,但SU目录下不存在2023/01这类子目录,导致无法创建文件。
  • 如果../SU目录本身不存在,同样会触发FileNotFoundError。

修正后的代码

先处理日期格式确保文件名合法,同时自动创建目标目录(不存在时):

import os

date = input("Enter today's date: ").replace("/", "-")  # 将/替换为-,避免被解析为路径分隔符
mood = input("How do you rate your mood today from 1 to 10? ")
thought = input("Let your thoughts flow:\n")

# 定义目标目录和文件路径
target_dir = "../SU"
file_path = os.path.join(target_dir, f"{date}.txt")

# 自动创建目标目录(exist_ok=True避免目录已存在时报错)
os.makedirs(target_dir, exist_ok=True)

with open(file_path, 'w') as file:
    file.write(f"{mood}\n\n")
    file.write(f"{thought}\n\n")

多种文件操作示例

1. 基础创建文件(覆盖已有内容)

确保目标目录存在后,创建或覆盖文件:

import os

file_dir = "./notes"
file_path = os.path.join(file_dir, "first_note.txt")

os.makedirs(file_dir, exist_ok=True)

# 'w'模式:文件存在则覆盖,不存在则创建
with open(file_path, 'w') as f:
    f.write("这是第一个笔记内容\n")

2. 追加内容到已有文件

使用a模式在文件末尾添加内容,不会覆盖原有内容:

file_path = "./notes/first_note.txt"

# 'a'模式:文件存在则追加,不存在则创建
with open(file_path, 'a') as f:
    f.write("这是追加的内容\n")
    f.write("继续追加一行\n")

3. 创建文件并写入多行内容

支持两种写入多行内容的方式:

lines = [
    "第一行内容\n",
    "第二行内容\n",
    "第三行内容\n"
]

with open("./notes/multi_line.txt", 'w') as f:
    # 方式1:用writelines写入列表
    f.writelines(lines)
    
    # 方式2:直接写入多行字符串
    f.write("\n另一段多行内容:\n这是第一行\n这是第二行")

4. 批量创建文件

通过循环快速生成多个文件:

import os

batch_dir = "./batch_notes"
os.makedirs(batch_dir, exist_ok=True)

for i in range(1, 6):
    file_path = os.path.join(batch_dir, f"note_{i}.txt")
    with open(file_path, 'w') as f:
        f.write(f"这是第{i}个批量创建的文件内容")

5. 安全写入(避免编码问题)

指定编码格式,防止中文等非ASCII字符乱码:

with open("./notes/chinese_note.txt", 'w', encoding='utf-8') as f:
    f.write("这是中文内容,指定utf-8编码避免乱码")

内容的提问来源于stack exchange,提问作者Mohit Sahu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 06:55:56