简体   繁体   English

如果使用python不存在,请创建多个文件夹

[英]Create multiple folders if it does not exist using python

I have several xml files(more than 20000) present in one directory. 我在一个目录中有几个xml文件(超过20000个)。 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). 我需要从每个xml文件中获取应用程序文件夹名称,然后将文件移动到其各自的应用程序文件夹(两个文件的应用程序名称可以相同)。

With "if not os.path.exists('Working_Dir/app'):" I am trying to check for each application if it is present or not. 使用"if not os.path.exists('Working_Dir/app'):"我正在尝试检查每个应用程序是否存在。 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'

I think this links maybe help you. 我认为这个链接可能对你有帮助。

  1. python-2-6-file-exists-errno-17 蟒蛇-2-6-文件存在,错误号-17
  2. python-fileexists-error-when-making-directory 蟒蛇-FILEEXISTS错误-当制定目录

I think what you do is just to raise the exception.I can not reappear your Exception. 我认为你所做的只是提出异常。我无法再出现你的异常。

shutil.move('Working_Dir/f.name', 'Working_Dir/app') Is this correct? shutil.move('Working_Dir/f.name', 'Working_Dir/app')这是对的吗? I think it is trying to search f.name in the working directory. 我认为它试图在工作目录中搜索f.name 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM