python 压缩多个文件

python zipfile multiple files

我在使用 python 和 zipfile 时遇到问题,即:我无法向我的 zip 添加第二个文件。 这是我的代码,如果您需要更多,我很乐意提供。

def zipDir(fn_source, fn_destinationFolder):
  ''' fn_destinationFolder = folder to zip
      fn_source = destination path for the zip
  '''
  fn_zipfileName = os.path.join(os.path.dirname(os.path.basename(fn_source)),fn_destinationFolder)+'.zip'

  with zipfile.ZipFile(fn_zipfileName, 'w') as fn_zipfile:
    for csvFile in os.listdir(fn_destinationFolder):
#     fn_zipfile.write(csvFile)
      if csvFile.endswith('.csv'):
        try:
          # fn_zipfile.write(os.path.join(fn_destinationFolder,csvFile))   ## write the whole filestructure to zip, '/home/uname/.../xyz.zip'
          fn_zipfile.write(csvFile)                                       ## write only the file to zip  'xyz.zip'
        except IOError:
          None
          print('did not add',csvFile,'to',fn_zipfile)
    fn_zipfile.printdir()
  return fn_zipfileName

在 "test" 目录中,我有 2 个文件:"example.csv" 和 "example1.csv" 这会导致以下错误:

python3.5 removing_the_header_from_CSV.py --from test --to zip
Removed headers from example.csv
Removed headers from example1.csv
did not add example1.csv to <zipfile.ZipFile filename='/home/xxx/repos/automate_the_boring_stuff/14_csv_files_and_json_data/NEW_test_2016-05-22_12-19-23.zip' mode='w'>
File Name                                             Modified             Size
example.csv                                    2016-05-20 17:12:19          191
zipfile can be found at /home/xxx/repos/automate_the_boring_stuff/14_csv_files_and_json_data/NEW_test_2016-05-22_12-19-23.zip

如果我只使用 "fn_zipfile.write(csvFile)",我会得到这个额外的信息:

python3.5 removing_the_header_from_CSV.py --from test --to zip
Removed headers from example.csv
Removed headers from example1.csv
Traceback (most recent call last):
  File "removing_the_header_from_CSV.py", line 169, in <module>
main()
  File "removing_the_header_from_CSV.py", line 156, in main
zipfileName = zipDir(source, destinationFolder)
  File "removing_the_header_from_CSV.py", line 112, in zipDir
fn_zipfile.write(csvFile)
  File "/usr/lib/python3.5/zipfile.py", line 1433, in write
st = os.stat(filename)
FileNotFoundError: [Errno 2] No such file or directory: 'example1.csv'

我用不同的文件尝试过这个,结果总是一样的,除非我的测试目录中只有 1 个文件。然后,一切都按预期工作。

您的一个问题是您正在列出某个远程 source 目录的内容,出于某种原因称为 fn_destinationFolder],获取文件名,过滤 .csv - 仅小写,然后告诉 zipfile 添加文件名。这就像对 伦敦 的某人说,在检查 纽约 [=20] 这些街道存在后,在 1st 和 Main 的交界处找一辆黄色出租车=] 那里有出租车站。

确保传递 fn_zipfile.write 输入文件的完整路径 - 您也可以覆盖 zip 文件中的名称,例如:

fn_zipfile.write(os.path.join(fn_destinationFolder, csvFile), csvFile)