2017-12-18 145 views
3

我正在嘗試讀取其中包含1個csv文件的zip文件。在R中讀取zip文件而不知道其中的csv文件名

當我知道csv文件名時,它工作的很好,但是當我試圖單獨提取zip文件時,它不起作用。

下面是其中它不工作的例子:

read.table(zip_file, skip = 10, nrows=10, header=T, quote="\"", sep=",") 

錯誤出現:

zip_file <- abc.zip 
csv_file <- abcde.csv 

data <- read.table(unz(zip_file,csv_file), skip = 10, header=T, quote="\"", sep=",") 

這裏是不會當我試圖只能提取zip文件工作他說:

Error in read.table(attachment_file, skip = 10, nrows = 10, header = T, : 
    no lines available in input 
In addition: Warning messages: 
1: In readLines(file, skip) : line 2 appears to contain an embedded nul 
2: In readLines(file, skip) : line 3 appears to contain an embedded nul 
3: In readLines(file, skip) : 
    incomplete final line found on 
'C:\Users\nickk\AppData\Local\Temp\RtmpIrqdl8\file2c9860d62381' 

所以這說明肯定是有存在CSV文件,因爲它的工作原理,當我包括CSV˚F ile的名字,但當我只是做的zip文件,然後錯誤出現。

對於上下文來說,我不想包含csv文件名的原因是因爲我需要每天讀取這個zip文件,並且csv文件的名稱每次都會改變而沒有任何模式。所以我的目標是隻讀取zip文件來繞過這個。

謝謝!

+0

您無需爲['read.table'](http://stat.ethz.ch/R-manual/R-devel/library/utils/html/read.table)專門解壓縮文件.html)(請參閱'file'說明)。嘗試:'data < - read.table(zip_file,skip = 10,header = T,quote =「\」「,sep =」,「)' – m0nhawk

+2

也許用'unzip(zip_file,list = TRUE) ,然後使用該文件名作爲您的變量csv_file。 – Florian

+0

@Florian工作很好! –

回答

3

你爲什麼不嘗試使用unzip找到ZIP壓縮包內的文件名:

zipdf <- unzip(zip_file, list = TRUE) 
# the following line assuming the archive has only a single file 
csv_file <- zipdf$Name[0] 

your_df <- read.table(csv_file, skip = 10, nrows=10, header=T, quote="\"", sep=",") 
0

如果你是開放的data.table,你可以嘗試:

data.table::fread(paste('unzip -cq', zip_file), skip = 10) 
  • -c:解壓出色;
  • -q:壓制由unzip打印的郵件;