codehaus


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

fileinput module not yielding expected results


On 9/7/19 11:12 AM, Jason Friedman wrote:

> $ grep "File number" ~/result | sort | uniq
> File number: 3
> 
> I expected that last grep to yield:
> File number: 1
> File number: 2
> File number: 3
> File number: 4
> File number: 5
> File number: 6

As per https://docs.python.org/3/library/fileinput.html#fileinput.fileno,
fileno is the underlying file descriptor of the file, and not at
all what you're looking for.

> My ultimate goal is as follows. I have multiple CSV files, each with the
> same header line. I want to read the header line from the first file and
> ignore it for subsequent files.

If you're certain that the headers are the same in each file,
then there's no harm and much simplicity in reading them each
time they come up.

     with fileinput ...:
         for line in f:
             if fileinput.isfirstline():
                 headers = extract_headers(line)
             else:
                 pass # process a non-header line here

Yes, the program will take slightly longer to run.  No, you won't
notice it.