我想把我的程序的输出信息到一个文件夹。如果给定的文件夹不存在,那么程序应该创建一个新的文件夹,文件夹名称为程序中给定的。这可能吗?如果是,请告诉我怎么做。

假设我已经给出了文件夹路径像“C:\Program Files\alex”和alex文件夹不存在,那么程序应该创建alex文件夹,并应该把输出信息放在alex文件夹。


你试过os.mkdir吗?

你也可以试试下面这个小代码片段:

mypath = ...
if not os.path.isdir(mypath):
   os.makedirs(mypath)

如果需要,Makedirs将创建多级目录。

你可以用os.makedirs()创建一个文件夹 并使用os.path.exists()查看它是否已经存在:

newpath = r'C:\Program Files\arbitrary' 
if not os.path.exists(newpath):
    os.makedirs(newpath)

如果你正在尝试制作安装程序:Windows安装程序为你做了很多工作。

你可能想要os。Makedirs,因为如果需要的话,它还会创建中间目录。

import os

#dir is not keyword
def makemydir(whatever):
  try:
    os.makedirs(whatever)
  except OSError:
    pass
  # let exception propagate if we just can't
  # cd into the specified directory
  os.chdir(whatever)