2017-07-03 115 views
3

我使用Julia的ZipFile包来提取和处理csv文件。没问题,但是当我在zip文件中遇到压缩文件时,我想要处理它,但遇到错误。Julia:在Zip文件中提取Zip文件

朱莉娅ZipFile的文档是在这里:https://zipfilejl.readthedocs.io/en/latest/

下面的代码:

using ZipFile 
using DataFrames 
function process_zip(zip::ZipFile.ReadableFile) 

    if split(zip.name,".")[end] == "zip" 

     r = ZipFile.Reader(zip) #error: MethodError: no method matching seekend(::ZipFile.ReadableFile) 

     for f in r.files 
      process_zip(f) 
     end 
    end 

    if split(zip.name,".")[end] == "csv" 
     df = readtable(zip) #for now just read it into a dataframe 
    end 

end 

r = ZipFile.Reader("yourzipfilepathhere"); 

for f in r.files 
    process_zip(f) 
end 
close(r) 

到ZipFile.Reader调用给出了错误:

MethodError: no method matching seekend(::ZipFile.ReadableFile) 
Closest candidates are: 
    seekend(::Base.Filesystem.File) at filesystem.jl:191 
    seekend(::IOStream) at iostream.jl:57 
    seekend(::Base.AbstractIOBuffer) at iobuffer.jl:178 
    ... 

Stacktrace: 
[1] _find_enddiroffset(::ZipFile.ReadableFile) at /home/chuck/.julia/v0.6/ZipFile/src/ZipFile.jl:259 
[2] ZipFile.Reader(::ZipFile.ReadableFile, ::Bool) at /home/chuck/.julia/v0.6/ZipFile/src/ZipFile.jl:104 
[3] process_zip(::ZipFile.ReadableFile) at ./In[27]:7 
[4] macro expansion at ./In[27]:18 [inlined] 
[5] anonymous at ./<missing>:? 

如此看来ZipFile的包无法处理来自zip文件的zip文件,因为它无法对它做一个seekend。

有关如何做到这一点的任何想法?

+0

我想你可能需要先解压缩zip文件,然后在提取后对它们进行递归。 – gaborous

+0

我应该解压缩到一个磁盘文件,还是我可以解压到一个内存文件?我是Julia的新手,我不知道如何创建内存文件。 –

+0

它似乎只适用于文件,但你可能会尝试通过将你的内存zip对象包装成一个类似文件的类来实现ZipFile操作zip对象所需的方法。但让我们看看是否有更多Julia经验的人可以为您提供更优雅的解决方案。 – gaborous

回答

2

解决方法是将zip文件读取到IOBuffer中。 ZipFile.Reader能够处理IOBuffer。这里是工作代码:

using ZipFile 
using DataFrames 
function process_zip(zip::ZipFile.ReadableFile) 

    if split(zip.name,".")[end] == "zip" 

     iobuffer = IOBuffer(readstring(zip)) 
     r = ZipFile.Reader(iobuffer) 

     for f in r.files 
      process_zip(f) 
     end 
    end 

    if split(zip.name,".")[end] == "csv" 
     df = readtable(zip) #for now just read it into a dataframe 
    end 

end 

r = ZipFile.Reader("yourzipfilepathhere"); 

for f in r.files 
    process_zip(f) 
end 
close(r)