Reading file issue

Oscar Benjamin oscar.j.benjamin at
Mon Jan 28 12:58:52 CET 2013

On 28 January 2013 11:47, loial <jldunn2000 at> wrote:
> I am parseing a file to extract data, but am seeing the file being updated even though I never explicitly write to the file. It is possible that another process is doing this at some later time, but I just want to check that opening the file as follows and ignoring a record would not result in that record being removed from the file.
> I'm damned sure it wouldn't, but just wanted to check with the experts!.
>         for line in open("/home/john/myfile"):

The line above opens the file in read-only mode. It's not possible to
make changes to the file if you only open it in read-only mode. So no
this code is not modifying the file. It is, however, slightly better
to write the above as

with open('/home/john/myfile') as fin:
    for line in fin:
        # stuff

This is better as the "with" statement handles errors better than just
calling open directly.

>             linecount = linecount + 1
>             if linecount == 1:  # ignore header
>                 continue

Another way of achieving this would be to do:

headerline = fin.readline()
for line in fin:
    # No need to worry about that header line now


More information about the Python-list mailing list