Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 创建100+;文件夹并按顺序命名_Python_Directory - Fatal编程技术网

Python 创建100+;文件夹并按顺序命名

Python 创建100+;文件夹并按顺序命名,python,directory,Python,Directory,我试图使用os.makedirs()工具创建143个文件夹,但遇到了一些问题。我一次只能生成一个文件夹,我想一次生成所有文件夹。我想将文件夹命名为IMG_0016到IMG_00160 我想尝试一个带有计数器的for循环,每个循环都会在文件夹标题的末尾添加新的数字,但我无法让它工作 import os for folders in range(0, 143): count = 0016 os.makedirs("C:\\Users\joshuarb\Desktop\Organi

我试图使用os.makedirs()工具创建143个文件夹,但遇到了一些问题。我一次只能生成一个文件夹,我想一次生成所有文件夹。我想将文件夹命名为IMG_0016到IMG_00160

我想尝试一个带有计数器的for循环,每个循环都会在文件夹标题的末尾添加新的数字,但我无法让它工作

import os

for folders in range(0, 143):
    count = 0016

    os.makedirs("C:\\Users\joshuarb\Desktop\Organized_Images\IMG"+count)

    count = count+1

每次循环迭代都要重新声明
count=0016
。把这个放在圈外

import os

count = 0016

for folders in range (0, 143):

    os.makedirs("C:\\Users\joshuarb\Desktop\Organized_Images
    IMG"+count)

    count = count+1

使用直拨号码更容易,可读性也更高(请注意,您希望在
range()
调用中使用161,因为最后一个号码不包括在内):


还请注意,我使用了宽度为4的零填充,因为IMG_0016和IMG_00160的命名约定不同,所以我选择限制为DOS通常的8个字符。根据需要进行调整。

停止手动跟踪
计数
并使用
范围的结果

first_num = 16
folder_count = 143
base_path = r"C:\Users\joshuarb\Desktop\Organized_Images"

for folder_num in range(first_num, first_num + folder_count):
    os.makedirs(os.path.join(base_path, "IMG"+str(folder_num).zfill(4)))

首先,对于这类任务,没有必要使用临时变量。使用可以并且应该使用在范围内迭代的变量

其次,
range
默认情况下从0创建范围,因此可以删除左侧间隔边界。对于您的特定任务,最好的方法是迭代所需的时间间隔:从16到160

第三,在Windows中,最好使用原始字符串来存储路径或屏蔽每个反斜杠,因为单个反斜杠被识别为元符号的开始

最新情况是,建议在连接字符串时使用
格式

因此,最终的解决方案可能如下所示:

import os
base_path = "C:\\Users\\joshuarb\\Desktop\\Organized_Images\\"
dir_basename = "IMG_00"
for index in range(16, 161):
    os.makedirs("{}{}{}".format(base_path, dir_basename, index))

使用
os.getcwd()
如果同一目录中的目标还提供了一些路径

您已经得到了一些很好的答案,但是作为建议,如果您不需要两个前导零,为什么不尝试将编号设置为IMG_0016到IMG_0160。如果您需要对它们进行排序,这会有所帮助。它修复了代码的主要问题。我知道他的代码不是很“好”,但当它超出问题范围时,我的工作不是为他修复代码。
import os
base_path = "C:\\Users\\joshuarb\\Desktop\\Organized_Images\\"
dir_basename = "IMG_00"
for index in range(16, 161):
    os.makedirs("{}{}{}".format(base_path, dir_basename, index))
import os

for folders in range(1,5):

    os.makedirs(os.getcwd()+'/folder00'+ str(folders))