【问题标题】:Create multiple folders if it does not exist using python如果它不存在使用python创建多个文件夹
【发布时间】:2015-09-12 20:11:01
【问题描述】:

我在一个目录中有多个 xml 文件(超过 20000 个)。我需要从每个 xml 文件中获取应用程序文件夹名称,然后将文件移动到其各自的应用程序文件夹(两个文件的应用程序名称可以相同)。

对于"if not os.path.exists('Working_Dir/app'):",我正在尝试检查每个应用程序是否存在。下一行我正在尝试创建该文件夹,但不知何故它没有检查文件夹是否存在。

 #!/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)

以下是我得到的错误。

$ 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'

【问题讨论】:

    标签: python


    【解决方案1】:

    我认为此链接可能对您有所帮助。

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

    我认为您所做的只是引发异常。我无法重新出现您的异常。

    【讨论】:

    • 谢谢,在将此错误保留为异常后它正在工作。
    • 创建文件夹后,我尝试将文件移动到相应的文件夹,但这会引发错误。 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') 下面是错误:IOError: [Errno 2] No such file or directory: 'Working_Dir/f.name'
    【解决方案2】:

    shutil.move('Working_Dir/f.name', 'Working_Dir/app')这是正确的吗? 我认为它正在尝试在工作目录中搜索f.name。 看看这是否有帮助:

    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)
    

    【讨论】:

      猜你喜欢
      • 2013-11-05
      • 2020-07-12
      • 2022-01-11
      • 1970-01-01
      • 2011-01-19
      • 2014-07-20
      • 2013-09-18
      • 1970-01-01
      相关资源
      最近更新 更多