如何创建新文件夹?

176 python mkdir

我想将程序的输出信息放到一个文件夹中.如果给定文件夹不存在,则程序应该创建一个新文件夹,文件夹名称与程序中给出的一样.这可能吗?如果是,请告诉我如何.

假设我已经给出了文件夹路径,"C:\Program Files\alex"并且alex文件夹不存在则程序应该创建alex文件夹,并且应该将输出信息放在alex文件夹中.

mca*_*dre 281

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

newpath = r'C:\Program Files\arbitrary' 
if not os.path.exists(newpath):
    os.makedirs(newpath)
Run Code Online (Sandbox Code Playgroud)

如果您正在尝试制作安装程序:Windows Installer会为您做很多工作.

  • 做`os.path.join('dir','other-dir')`而不是`dir\other-dir`如果你想与windows之外的东西兼容. (25认同)
  • 这将失败,因为在os.makedirs的调用中没有双反斜杠. (9认同)
  • 因为os.path函数使用运行路径字符串脚本的python安装的本地规则.在所有情况下使用os.path.join可确保为正在运行脚本的平台正确形成路径. (3认同)
  • 它杀了我:newpath = r'C:\ Program Files\alex'; 如果不是os.path.exists(newpath):os.makedirs(newpath) (2认同)
  • 有人可以解释为什么 os.path.join('dir','other-dir') 与其他系统更兼容吗?因为斜杠/反斜杠? (2认同)

Jue*_*gen 36

你试过os.mkdir吗?

您也可以尝试这个小代码片段:

mypath = ...
if not os.path.isdir(mypath):
   os.makedirs(mypath)
Run Code Online (Sandbox Code Playgroud)

如果需要,makedirs会创建多个级别的目录.


Ale*_*lli 36

你可能想要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)
Run Code Online (Sandbox Code Playgroud)

  • ‘whatever’ 是一条路径吗? (2认同)