在python3中创建多个目录

时间:2018-03-22 18:27:43

标签: python windows python-3.x error-handling directory

我正在尝试在python中创建多个目录,但它说该文件不存在,即使我刚刚在代码上面创建它,下面的帮助将非常感激。

import os
import shutil

# err
if os.path.isdir(r'\Users\Oran\Documents\Sync\Files\Projects/testProject'):

    shutil.rmtree(r'\Users\Oran\Documents\Sync\Files\Projects/testProject')


# Main
os.chdir(r'\Users\Oran\Documents\Sync\Files\Projects')
os.mkdir('testProject')
os.chdir('testProject')
f = open("index.html", "wt")


dir_names = ["assets", "css"]
for x in (dir_names):
os.mkdir(x)

os.chdir('css/')
f = open("index.css", "wt")

os.chdir('assets/')

dir_names = ["img", "css", "js"]
for x in (dir_names):
os.mkdir(x)

os.chdir('js/')
f = open("index.js", "wt")

输出

[Running] python         
"c:\Users\Oran\Documents\Sync\Files\Projects\PYProjetCreator\index.py"
Traceback (most recent call last):
File 
"c:\Users\Oran\Documents\Sync\Files\Projects\PYProjetCreator\index.py", line 
24, in <module>
os.chdir('assets/')
FileNotFoundError: [WinError 2] The system cannot find the file specified: 
'assets/'

[Done] exited with code=1 in 0.089 seconds

1 个答案:

答案 0 :(得分:0)

您尝试将目录更改为testProject/css/assets文件夹而不是testProject/assets文件夹。

css文件夹到达目的地的最快捷方式是使用类似os.chdir('..\assets')的内容,但有很多其他方法可以使用os.pardir和其他os.path操作进行操作