On Jan 7, 7:15 pm, jo3c <[EMAIL PROTECTED]> wrote:
> hi everybody
> im a newbie in python
> i need to read line 4 from a header file
> using linecache will crash my computer due to memory loading, because
> i am working on 2000 files each is 8mb
>
> fileinput don't load the file into memory first
> how do i use fileinput module to read a specific line from a file?
>
> for line in fileinput.Fileinput('sample.txt')
> ????

Assuming it's a text file, you could use something like this:

lnum = 0 # line number

for line in file("sample.txt"):
    lnum += 1
    if lnum >= 4: break

The variable "line" should end up with the contents of line 4 if I am
not mistaken. To handle multiple files, just wrap that code like this:

for file0 in files:

    lnum = 0 # line number

    for line in file(file0):
        lnum += 1
        if lnum >= 4: break

    # do something with "line"

where "files" is a list of the files to be read.

That's not tested.
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to