我想把我的程序的输出信息放到一个文件夹里。如果给定的文件夹不存在,则程序应使用程序中给定的文件夹名称创建一个新文件夹。这个是可能的吗?如果是,请告诉我怎么做。
假设我已经给出了"C:\Program Files\alex"
这样的文件夹路径,并且alex
文件夹不存在,那么程序应该创建alex
文件夹,并将输出信息放在alex
文件夹中。
发布于 2009-08-13 20:43:38
您可以使用os.makedirs()创建文件夹
并使用os.path.exists()查看它是否已经存在:
newpath = r'C:\Program Files\arbitrary'
if not os.path.exists(newpath):
os.makedirs(newpath)
如果你正在尝试制作一个安装程序:Windows Installer会为你做很多工作。
发布于 2009-08-13 20:39:10
你试过os.mkdir吗?
您还可以尝试以下小代码片段:
mypath = ...
if not os.path.isdir(mypath):
os.makedirs(mypath)
如果需要,makedirs会创建多级目录。
发布于 2009-08-13 20:46:12
您可能需要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)
https://stackoverflow.com/questions/1274405
复制相似问题