在R中读取zip文件而不知道其中的csv文件名

问题描述 投票:3回答:2

我正在尝试读取一个包含1个csv文件的zip文件。

当我知道csv文件名时,它工作得很好,但当我只是尝试单独提取zip文件时,它不起作用。

以下是它的工作原理示例:

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

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

当我尝试仅提取zip文件时,这是不起作用的地方:

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

出现错误说:

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文件名时起作用,但是当我只是执行zip文件时,则出现错误。

对于上下文,我不想包含csv文件名的原因是因为我需要每天读取此zip文件,并且csv文件的名称每次都不会更改。所以我的目标是只读取zip文件以绕过它。

谢谢!

r csv zip unzip read.table
2个回答
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印刷的消息;
© www.soinside.com 2019 - 2024. All rights reserved.