如何从r中的gzip文件中读取行?

use*_*468 5 r

我需要从gzip文件读取小批量的行(一次说100条),该文件是使用gzip压缩的文本文件。我使用小批量,因为每行都非常长。

但是我不能用这样的东西(我认为缓冲区没有更新):

in.con <- gzfile("somefile.txt.gz")
for (i in 1:100000) {
  chunk <- readLines(in.con,n = 100)
  # if you inspect chunk in each loop step, say with a print
  # you will find that chunk updates once or twice and then
  # keeps printing the same data.
}
close(in.con)
Run Code Online (Sandbox Code Playgroud)

我如何完成类似的工作?

笔记:

  1. 对于小文件,这将起作用。
  2. 您将需要一个非常大的文件,并且当您尝试多次读取它时–您会看到chunk变量不会更新
  3. 我认为这是因为基础扫描对gzip文件不可靠
  4. i变量只是为了限制循环-不需要引用i
  5. 一些评论似乎在说该代码不适用于文本文件-我发布的结果显示如下:

in.con <- file("some.file.txt", "r", blocking = FALSE)
while(TRUE) {
  chunk <- readLines(in.con,n = 2)
  if (length(chunk)==0) break;
  print(chunk)
}
close(in.con)
Run Code Online (Sandbox Code Playgroud)

产生输出:

[1] "1" "2"
[1] "3" "4"
[1] "5" "6"
[1] "7" "8"
[1] "9"  "10"
Run Code Online (Sandbox Code Playgroud)

我的版本信息是:

platform       x86_64-apple-darwin15.6.0   
arch           x86_64                      
os             darwin15.6.0                
system         x86_64, darwin15.6.0        
status                                     
major          3                           
minor          4.1                         
year           2017                        
month          06                          
day            30                          
svn rev        72865                       
language       R                           
version.string R version 3.4.1 (2017-06-30)
nickname       Single Candle     
Run Code Online (Sandbox Code Playgroud)

小智 4

这是 中的一个错误gzfile()。对于大文件,如果不open指定参数,则会一遍又一遍地读取同一行。

> incon <- gzfile(zfile)
> readLines(incon,1)
[1] First line
> readLines(incon,1)
[1] First line
Run Code Online (Sandbox Code Playgroud)

即使open指定了参数,它也只会导致错误。

> incon <- gzfile(zfile,open="r")
> line <- readLines(incon,1)
Warning message:
In readLines(incon, 1) :
  seek on a gzfile connection returned an internal error
Run Code Online (Sandbox Code Playgroud)

解决方案:作为一种解决方法,可以file()在二进制读取模式下使用常规连接并将其包装在gzcon()

> incon <- gzcon(file(zfile,open="rb"))
> readLines(incon,1)
[1] First line
> readLines(incon,1)
[1] Second line
Run Code Online (Sandbox Code Playgroud)