python .os.path.walk与直接文件

时间:2012-06-15 18:20:52

标签: python

/home/username/main/books/目录中的所有内容都会被写入并返回,但/home/username/main/index.html不会被写入,因为“index.html”不是目录,因此无法行走。我如何修改脚本来说明它是否是一个目录,然后把它写下来然后写下它找到的所有东西,如果是它的直接文件,写下来。

def zipit (request):
  file_paths = ['/home/username/main/books/', '/home/username/main/index.html']
  buffer= StringIO.StringIO()
  z= zipfile.ZipFile( buffer, "w" )
  for p in file_paths:
    for dir, subdirs, files in os.walk(p):
      for f in files:
        filename = os.path.join(dir, f)
        z.write(filename, arcname = filename[15:])
  z.close()
  buffer.seek(0)
  final = HttpResponse(buffer.read())
  final['Content-Disposition'] = 'attachment; filename=dbs_custom_library.zip'
  final['Content-Type'] = 'application/x-zip'
  return final

1 个答案:

答案 0 :(得分:1)

您需要在步行前检查p

  • 如果是目录=>走进。
  • 如果不是=>只需将此文件添加到存档。

修改后的代码:

def zipit (request):
  file_paths = ['/home/username/main/books/', '/home/username/main/index.html']
  buffer= StringIO.StringIO()
  z= zipfile.ZipFile( buffer, "w" )
  for p in file_paths:
    if os.path.isdir(p):
      for dir, subdirs, files in os.walk(p):
        for f in files:
          filename = os.path.join(dir, f)
          z.write(filename, arcname = filename[15:])
     else:
          z.write(p, arcname = p)
  z.close()
  buffer.seek(0)
  final = HttpResponse(buffer.read())
  final['Content-Disposition'] = 'attachment; filename=dbs_custom_library.zip'
  final['Content-Type'] = 'application/x-zip'
  return final