如何创建新文件夹?

337 投票
3 回答
730993 浏览
提问于 2025-04-15 13:35

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

假设我给定的文件夹路径是 "C:\Program Files\alex",而 alex 文件夹不存在,那么程序应该创建 alex 文件夹,并把输出信息放到这个 alex 文件夹里。

3 个回答

48

你可能想用 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)
73

你试过用 os.mkdir 吗?

你也可以试试这个小代码:

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

makedirs 可以创建多层文件夹,如果需要的话。

531

你可以使用 os.makedirs() 来创建一个文件夹。
同时,你可以用 os.path.exists() 来检查这个文件夹是否已经存在:

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

如果你想制作一个安装程序的话,Windows Installer 可以帮你完成很多工作。

撰写回答