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

Python代码检测当前目录指定文件夹是否存在及后续处理方法

Python实现检测并创建文件夹后存储内容

可以通过两种常用方式实现需求:使用传统的os模块,或者Python3.4+推荐的pathlib模块(更简洁直观)。

方法一:使用os模块

import os

# 获取当前脚本所在的code_folder目录
current_dir = os.path.dirname(os.path.abspath(__file__))
# 拼接目标文件夹路径
target_folder = os.path.join(current_dir, "folder_1")

# 创建文件夹(如果不存在则创建,存在则忽略)
os.makedirs(target_folder, exist_ok=True)

# 在folder_1中存储内容,示例为写入test.txt文件
file_path = os.path.join(target_folder, "test.txt")
with open(file_path, "w", encoding="utf-8") as f:
    f.write("要存储的内容")

代码说明:

  • os.path.abspath(__file__) 获取当前脚本的绝对路径,os.path.dirname() 提取其所在目录(即code_folder)
  • os.makedirs(..., exist_ok=True) 递归创建文件夹,exist_ok=True 参数确保文件夹已存在时不会抛出异常
  • 使用with open()上下文管理器安全地写入文件内容

方法二:使用pathlib模块(推荐)

from pathlib import Path

# 获取当前脚本所在的code_folder目录
current_dir = Path(__file__).parent.resolve()
# 拼接目标文件夹路径
target_folder = current_dir / "folder_1"

# 创建文件夹(如果不存在则创建,存在则忽略)
target_folder.mkdir(exist_ok=True, parents=True)

# 在folder_1中存储内容,示例为写入test.txt文件
file_path = target_folder / "test.txt"
file_path.write_text("要存储的内容", encoding="utf-8")

代码说明:

  • Path(__file__).parent.resolve() 获取当前脚本所在的绝对目录
  • 使用/操作符拼接路径,比os.path.join()更直观
  • mkdir(exist_ok=True, parents=True) 创建文件夹,parents=True确保父目录不存在时也能递归创建(这里父目录是code_folder,一般已存在,但加上更稳妥)
  • write_text() 方法可以直接写入文本内容,无需手动打开/关闭文件

两种方法都能实现需求,pathlib的语法更简洁,符合现代Python的风格。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 02:01:12