在Directory python中创建子文件夹时出错

时间:2018-04-06 21:18:06

标签: python python-3.x python-2.7

import os
#Folders Creation
for folderName, subfolders, filenames in os.walk('I:\DATA\Train'):
    print('The current folder is ' + folderName)

    for filename in filenames:
        filename=os.path.splitext(filename)[0]
        os.makedirs(filename, exist_ok=True)
        print(filename)

    print('')
#Sub Folders Creation
path="C:\DATA"
for folderName, subfolders, filenames in os.walk(path):
    print('The current folder is ' + folderName)

    for subfolder in subfolders:
        print('SUBFOLDER OF ' + folderName + ': ' + subfolder)
        mypath = os.path.join(path,str(subfolder))
        os.chdir(mypath)
        os.getcwd()
        os.makedirs("test",exist_ok=True)
        os.makedirs("train",exist_ok=True)
        os.close

    print('') 

此代码有效,但也会抛出错误但是当我在路径上创建测试和训练文件夹时,如果没有在路径中创建测试和训练,错误就会消失如何解决这个问题

获取此错误

FileNotFoundError: [WinError 2] The system cannot find the file specified: 'C:\\DATA\\test'

2 个答案:

答案 0 :(得分:0)

请尝试以下代码。 os.chdir(mypath)和os.getcwd()这些行似乎不适合你。

for subfolder in subfolders:
    print('SUBFOLDER OF ' + folderName + ': ' + subfolder)
    mypath1 = os.path.join(path,str(subfolder),"test")
    mypath2 = os.path.join(path,str(subfolder),"train")
    os.makedirs(mypath1,exist_ok=True)
    os.makedirs(mypath2,exist_ok=True)
    os.close

答案 1 :(得分:-1)

尝试更改' \' ,并使用' /'为路径。