Skip to content

Scanning data files line-by-line

4 messages · R A F, Brian Ripley, Duncan Murdoch

#
Maybe I'm missing something.  When I do readLines( "file", n = 1) and
repeat, it always reads the first line of "file".  I've to be able to
advance to the next line, no?

I'll take a look at the command file(), as someone else suggested.

Thanks.
#
On Wed, 30 Apr 2003, R A F wrote:

            
You need to open the connection first.  readLines( "file", n = 1)
opens file "file", reads a line and then closes "file".  It has no idea
that you want to keep reading the same file.
It's open() you need, as in

con <- file("file")
open(con)
for(i in 1:10) print(readLines(con, n=1))
close(con)

In C you would need to (f)open a file to read it line-by-line, just as 
here.

The first two lines can be collapsed to

con <- file("file", "r")

  
    
#
On Wed, 30 Apr 2003 12:45:33 +0000, RAF wrote:

            
Yes, that's your solution.  

con <- file("foo") 

will open the file called foo and attach it to a connection called
con.  You pass con to readLines, and since the file stays open between
calls, you'll get successive lines.  Remember close(con) when you're
done.

Duncan Murdoch
#
On Wed, 30 Apr 2003 09:19:20 -0400, I wrote:

            
Whoops, believe Brian, not me.  You need 

 con <- file("file", "r")

Duncan Murdoch