以编程方式使用Python创建文件目录?

时间:2018-06-07 21:21:07

标签: python python-2.7

我正在尝试使用python创建一系列文件夹和子文件夹,但我无法正确使用它。我一直收到一个错误,我在同一个文件夹中创建了我当前所在文件夹的文件夹。我无法弄清楚如何直截了当。

import os, sys, errno

all_dirs = {
    'audio': ['Music', 'Audiobooks', 'Podcasts'],
    'documents': ['Forms', 'Bills', 'Legal', 'Financial'],
    'images': ['Photographs','Art', 'Friends', 'Family'],
    'literature': ['Novels', 'Poetry', 'Short Stories'],
    'software': ['Apps', 'Games'],
    'videos': ['TV Series', 'Movies', 'Documentaries']
}

def create_dirr(curr_dirr, dirs_to_create):
  if not os.path.exists(curr_dirr):
    try:
      os.makedirs(curr_dirr)
    except OSError as exc:  # Guard against race condition
      if exc.errno != errno.EEXIST:
        raise
  else:
    print 2, os.getcwd()
    for dirr in dirs_to_create:
      print 2.5, dirr, os.getcwd()
      os.path.join(os.getcwd(), curr_dirr)
      print 2.7, os.getcwd(), os.path.join(os.getcwd(), dirr)
      os.chdir(os.path.join(os.getcwd(), curr_dirr))
      # os.path.join(ff, dirr)
      print 2.8, os.getcwd()
      # os.makedirs(dirr)
      # os.chdir(os.path.join(os.getcwd(), curr_dirr))
      print 2.9, dirr, os.getcwd()
      vv = os.path.join(os.getcwd(), dirr)
      print 3, dirr, os.getcwd()
      print 4, os.path.exists(dirr)
      print 5, vv
      print 7, dirr, os.getcwd()
      print '------------------------------------'
      if not os.path.exists(vv):
        print "here"
        try:
          print 6, vv
          # os.makedirs(vv)
        except OSError as exc:  # Guard against race condition
          if exc.errno != errno.EEXIST:
            raise
for x in all_dirs:
  create_dirr(x, all_dirs[x])
  create_dirr(x, all_dirs[x])

这是输出和错误代码:

2 /home/runner
2.5 Forms /home/runner
2.7 /home/runner /home/runner/Forms
2.8 /home/runner/documents
2.9 Forms /home/runner/documents
3 Forms /home/runner/documents
4 False
5 /home/runner/documents/Forms
7 Forms /home/runner/documents
------------------------------------
here
6 /home/runner/documents/Forms
2.5 Bills /home/runner/documents
2.7 /home/runner/documents /home/runner/documents/Bills
Traceback (most recent call last):
  File "python", line 130, in <module>
  File "python", line 104, in create_dirr
OSError: [Errno 2] No such file or directory: '/home/runner/documents/documents'

2 个答案:

答案 0 :(得分:0)

当您创建os.chdir时,尚未创建子文件夹。轻松修复

在make os.chdir make之前

os.makedirs(os.path.join(os.getcwd(), curr_dirr), exist_ok=True)

答案 1 :(得分:0)

我明白了。

首先,我在循环之前为os.getcwd()创建了一个变量。然后,我将其os.path.joincurr_dirrdirr合并。我还删除了os.chdir()

结果:

def create_dirr(curr_dirr, dirs_to_create):
  if not os.path.exists(curr_dirr):
    try:
      os.makedirs(curr_dirr)
    except OSError as exc:  # Guard against race condition
      if exc.errno != errno.EEXIST:
        raise
  else:
    print 2, os.getcwd()
    cd = os.getcwd()
    for dirr in dirs_to_create:
      print 2.5, dirr, os.getcwd(), os.path.join(cd, curr_dirr)
      print 2.7, os.path.join(cd, curr_dirr, dirr)
      print 2.8, cd
      print 3, dirr, cd
      print '------------------------------------'
      if not os.path.exists(os.path.join(cd, curr_dirr, dirr)):
        print "here"
        try:
          print 6, os.path.join(cd, curr_dirr, dirr)
          os.makedirs(os.path.join(cd, curr_dirr, dirr))
        except OSError as exc:  # Guard against race condition
          if exc.errno != errno.EEXIST:
            raise

使用此snippet来布局文件结构,我能够看到它的工作。

for root, dirs, files in os.walk("."):
    path = root.split(os.sep)
    print((len(path) - 1) * '---', os.path.basename(root))
    for file in files:
        print(len(path) * '---', file)