如何新建文件夹?

2024-04-23 14:12:05 发布

您现在位置:Python中文网/ 问答频道 /正文

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

假设我给定的文件夹路径像"C:\Program Files\alex"alex文件夹不存在,那么程序应该创建alex文件夹并将输出信息放在alex文件夹中。


Tags: 路径程序文件夹名称信息filesprogramalex
3条回答

您可能需要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)

你试过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 Installer为你做了很多工作。

相关问题 更多 >