4

I have several xml files(more than 20000) present in one directory. I need to get the application folder name from each xml file then move the file to its respective application folder (application name can be same for two files).

With "if not os.path.exists('Working_Dir/app'):" I am trying to check for each application if it is present or not. With next line I am trying to create that folder but somehow it is not checking for folder existence.

 #!/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 which 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'
satoru
  • 31,822
  • 31
  • 91
  • 141
ankitpandey
  • 339
  • 1
  • 7
  • 23

2 Answers2

1

I think this links maybe help you.

  1. python-2-6-file-exists-errno-17
  2. python-fileexists-error-when-making-directory

I think what you do is just to raise the exception.I can not reappear your Exception.

Community
  • 1
  • 1
chyoo CHENG
  • 720
  • 2
  • 9
  • 22
  • Thanks, It is working after keeping this error as exception. – ankitpandey Jun 26 '15 at 02:17
  • After creating folder i tried to move the file to respective folder but that is throwing error. if "ParentApplication" in line: app = line.split('.')[1] try: os.makedirs(app, 0755) except OSError as exception: if exception.errno != 17: raise shutil.move('Working_Dir/f.name', 'Working_Dir/app') Below is the error: IOError: [Errno 2] No such file or directory: 'Working_Dir/f.name' – ankitpandey Jun 26 '15 at 02:34
0

shutil.move('Working_Dir/f.name', 'Working_Dir/app') Is this correct? I think it is trying to search 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)
SKT
  • 174
  • 2
  • 17