繁体   English   中英

python zipfile多个文件

[英]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

在“测试”目录中,我有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个文件。 然后,一切正常。

您的问题之一是, 由于某种原因 ,您正在列出某个远程目录的内容,该目录称为fn_destinationFolder ,以获取文件名,仅过滤.csv(小写),然后告诉zipfile添加文件名。 这就像对伦敦的某人说的那样,在检查了纽约的街道并存在出租车等级之后,在1st和Main的交界处得到了一辆黄色出租车。

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

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

暂无
暂无

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

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