温馨提示×

python怎么批量生成文件名

小亿
112
2023-11-16 19:43:54
栏目: 编程语言

在Python中,可以使用循环结构来批量生成文件名。以下是一个示例:

import os

folder_path = '/path/to/folder'  # 指定文件夹路径
file_extension = '.txt'  # 文件扩展名

for i in range(1, 11):  # 循环生成文件名
    file_name = f"file_{i}{file_extension}"
    file_path = os.path.join(folder_path, file_name)
    with open(file_path, 'w') as file:
        # 在此处可以添加对文件的操作,例如写入内容等
        pass

上述代码中,我们首先指定了一个文件夹路径 folder_path 和一个文件扩展名 file_extension。然后使用 range 函数生成了一个从1到10的数字序列,通过循环遍历这些数字,生成对应的文件名。使用 os.path.join 函数将文件夹路径和文件名拼接在一起,得到完整的文件路径 file_path。最后使用 open 函数创建文件,并在需要的地方进行文件操作。

注意:在上述示例中,文件名的格式为 file_1.txtfile_2.txt 等。如果需要其他的文件名格式,可以根据需求进行修改。

0