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

Windows环境下如何用Python创建文件夹、写入N个文件并读取这些文件

在Windows环境下用Python创建文件夹、写入并读取文件的完整方案

嘿,我来帮你搞定这个问题~首先得指出你代码里的一个小坑:你最后用open(final_directory, "w")的时候,传入的是文件夹路径,而不是具体的文件路径,这肯定会报错,因为open()只能操作文件,不能直接操作目录。咱们一步步来修正并完成完整的流程:

1. 先导入必要的模块

处理文件和目录离不开os模块,先把它导入:

import os

2. 创建目标文件夹

你的思路是对的——从现有文件路径提取目录,再创建新文件夹。这里可以简化一下:os.makedirs()的exist_ok=True参数已经包含了“如果文件夹存在就不报错”的逻辑,不用额外写判断语句:

# 替换成你实际的原始文件路径
file_path = r"C:\Users\YourName\Documents\example.txt"

# 提取原始文件所在的目录
parent_dir = os.path.dirname(file_path)
# 拼接新文件夹的完整路径
target_folder = os.path.join(parent_dir, "new_folder")

# 创建文件夹(已存在则跳过)
os.makedirs(target_folder, exist_ok=True)

3. 向新文件夹写入N个文件

接下来咱们循环写入N个文件,比如写5个文本文件,每个文件带不同的内容:

N = 5  # 改成你需要的文件数量

for i in range(1, N+1):
    # 拼接每个文件的完整路径
    file_name = f"test_file_{i}.txt"
    full_file_path = os.path.join(target_folder, file_name)
    
    # 写入内容,记得加encoding避免Windows下中文乱码
    with open(full_file_path, "w", encoding="utf-8") as f:
        f.write(f"这是第{i}个测试文件的内容,Hello World!")

4. 读取新文件夹里的所有文件

现在我们可以遍历目标文件夹,读取每个文件的内容:

# 遍历文件夹内的所有条目
for item in os.listdir(target_folder):
    item_path = os.path.join(target_folder, item)
    # 只处理文件,跳过子文件夹
    if os.path.isfile(item_path):
        # 读取文件内容
        with open(item_path, "r", encoding="utf-8") as f:
            content = f.read()
            print(f"文件 {item} 的内容:\n{content}\n")

如果只想读取特定类型的文件(比如只读.txt),可以加个判断:if item.endswith(".txt")

完整可运行代码

把上面的步骤整合起来,就是可以直接运行的完整代码:

import os

# 配置参数
original_file_path = r"C:\Users\YourName\Documents\example.txt"  # 替换成你的路径
new_folder_name = "new_folder"
number_of_files = 5

# 创建目标文件夹
parent_directory = os.path.dirname(original_file_path)
target_directory = os.path.join(parent_directory, new_folder_name)
os.makedirs(target_directory, exist_ok=True)

# 写入N个文件
for idx in range(1, number_of_files + 1):
    file_path = os.path.join(target_directory, f"file_{idx}.txt")
    with open(file_path, "w", encoding="utf-8") as f:
        f.write(f"这是第{idx}个文件的测试内容,运行成功!")

# 读取所有文件并输出
print("=== 读取文件夹内的文件内容 ===")
for filename in os.listdir(target_directory):
    full_path = os.path.join(target_directory, filename)
    if os.path.isfile(full_path) and filename.endswith(".txt"):
        with open(full_path, "r", encoding="utf-8") as f:
            content = f.read()
            print(f"\n{filename}:")
            print(content)

内容的提问来源于stack exchange,提问作者Jammula Goud

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:29:34