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

Python如何基于用户输入批量生成两段式递增命名的文件

Python批量生成指定规则文件实现方案

核心实现逻辑

  • 通过input()获取用户输入的自定义前缀、前缀序号总数量,对数量输入做合法性校验,避免非数字输入报错
  • 采用双层循环匹配命名规则:外层循环遍历前缀序号,内层循环固定遍历1-4的后缀序号
  • 创建文件时默认使用x模式,避免意外覆盖已有同名文件,有覆盖需求可自行修改打开模式

完整可运行代码

def batch_create_files():
    # 获取自定义前缀
    custom_prefix = input("请输入自定义前缀(例如T):").strip()
    
    # 校验前缀总数量输入合法性
    while True:
        count_input = input("请输入前缀序号总生成数量:").strip()
        if count_input.isdigit() and int(count_input) > 0:
            prefix_total = int(count_input)
            break
        print("输入无效,请输入正整数")

    # 生成并创建文件
    for prefix_idx in range(1, prefix_total + 1):
        # 每个前缀对应4个后缀序号
        for suffix_idx in range(1, 5):
            file_name = f"{custom_prefix}{prefix_idx}_S{suffix_idx}.txt"
            try:
                # x模式仅当文件不存在时创建,防止覆盖已有文件
                with open(file_name, "x", encoding="utf-8") as f:
                    # 如果需要写入默认内容可以在这里添加代码
                    pass
                print(f"成功创建:{file_name}")
            except FileExistsError:
                print(f"已跳过存在的文件:{file_name}")

if __name__ == "__main__":
    batch_create_files()

补充说明

  • 如果你需要直接覆盖已存在的同名文件,将open方法的"x"参数修改为"w"即可
  • 如果需要指定文件保存的目录,在拼接file_name时加上路径前缀即可,比如file_name = f"C:/my_files/{custom_prefix}{prefix_idx}_S{suffix_idx}.txt"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 12:15:01