2017-12-18 213 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打印的邮件;