[R] Using readLines on a file without resetting internal file offset parameter?

Thomas Nyberg tomnyberg at gmail.com
Wed Oct 29 16:23:05 CET 2014


Hi everyone,

I would like to read a file line by line, but I would rather not load 
all lines into memory first. I've tried using readLines with n = 1, but 
that seems to reset the internal file descriptor's file offset after 
each call. I.e. this is the current behavior:

-------

bash $ echo 1 > testfile
bash $ echo 2 >> testfile
bash $ cat testfile
1
2

bash > R
R > f <- file('testfile')
R > readLines(f, n = 1)
[1] "1"
R > readLines(f, n = 1)
[1] "1"

-------

I would like the behavior to be:

-------

bash > R
R > f <- file('testfile')
R > readLines(f, n = 1)
[1] "1"
R > readLines(f, n = 1)
[1] "2"

-------

I'm coming to R from a python background, where the default behavior is 
exactly the opposite. I.e. when you read a line from a file it is your 
responsibility to use seek explicitly to get back to the original 
position in the file (this is rarely necessary though). Is there some 
flag to turn off the default behavior of resetting the file offset in R?

Cheers,
Thomas



More information about the R-help mailing list