每次执行 Python 程序时创建一个新目录

Create a new directory each time a Python program is executed

我需要在我的 Python 程序中创建一个新目录,每次执行它。比如第一次执行,目录

C:\Users\person\Desktop\Test_1

已创建

如果是第二次执行,目录

C:\Users\person\Desktop\Test_2

已创建

等等。如何实现?

Find all directories starting with Test_, find the one with the highest number, add 1 and create a new directory.

第一个也是最简单的方法就是解析目录结构,获取最后一个索引号,然后用新索引创建新目录。

如果您不熟悉创建目录,本主题将对您有用:How to check if a directory exists and create it if necessary?

此外 os.path 是你最好的朋友:https://docs.python.org/2/library/os.path.html#module-os.path

这是您的操作方法。

import os

root=r'/your/root/dir/here' #insert your directory where you want the new directory to be present

dirlist = [ item for item in os.listdir(root) if os.path.isdir(os.path.join(root,item)) ] 
 #has the list containing all the folder names

x=list(max(dirlist)) #finds the max number in the list and converts it into a list
y=x[-1]=int(x[-1])+int(('1')) #takes the last digit and adds one
path=r'/your/root/dir/here/test'+format(y) # make sure you have a folder already with a name test
os.makedirs(path, exist_ok=True) #creates a new dir everytime with max number