簡體   English   中英

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

[英]Reading a zip file in R without knowing the csv file name within it

我正在嘗試讀取一個包含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文件以繞過它。

謝謝!

為什么不嘗試使用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=",")

如果您對data.table開放data.table ,可以嘗試:

data.table::fread(paste('unzip -cq', zip_file), skip = 10)
  • -c :解壓縮到突出;
  • -qunzip打印的消息;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM