Create multiple folders if they don't exist using python

I have multiple xml files (over 20,000) present in the same directory. I need to get the application folder name from each xml file and then move the file to the corresponding application folder (the application name can be the same for two files).

C "if not os.path.exists('Working_Dir/app'):"

I am trying to check each application if it is present or not. On the next line, I try to create this folder, but for some reason it doesn't check for the existence of the folder.

 #!/usr/bin/python

import os, sys, glob

Working_Dir = "/home"
path1 = "/home/xmlFiles"
path2 = "/home/JobFolder"

if not os.path.exists(path1):
    os.mkdir(path1, 0755);

if not os.path.exists(path2):
    os.mkdir(path2, 0755);

for files in glob.glob("*.xml"):
    f = open( files)
    for line in f:
        if "ParentApplication" in line:
            app = line.split('.')[1]
            if not os.path.exists('Working_Dir/app'):
                os.makedirs(app)

      

Below is the error I am getting.

$ python test.py
Traceback (most recent call last):
  File "test.py", line 21, in <module>
    os.mkdir(app, 0755);
OSError: [Errno 17] File exists: 'TRC'

      

+3


source to share


2 answers


I think these links might help you.



I think you are only doing this to raise the exception. I cannot see my exception again.

0


source


shutil.move('Working_Dir/f.name', 'Working_Dir/app')

Is it correct? I think what it is trying to find f.name

in the working directory. See if this helps:



import os, sys, glob, errno, shutil`

Working_Dir = "/home"
path1 = "/home/xmlFiles"
path2 = "/home/JobFolder"

if not os.path.exists(path1):
os.mkdir(path1, 0755);

if not os.path.exists(path2):
os.mkdir(path2, 0755);

for files in glob.glob("*.py"):
 f = open( files)
 for line in f:
    if "test." in line:
        app = line.split('.')[1]
        print app
        try:
            print app
            os.makedirs(Working_Dir+'/'+app, 0755)
        except OSError as exception:
            if exception.errno != 17:
                raise
        s=Working_Dir+'/'+f.name
        t=Working_Dir+'/'+app+'/'
        shutil.move(s, t)

      

0


source







All Articles