fileinput module not yielding expected results

Jason Friedman jsf80238 at gmail.com
Sat Sep 7 12:44:30 EDT 2019


>
> 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.
>
> Ah, thank you Dan. I followed your advice ... the working code:

with fileinput.input(sys.argv[1:]) as f:
    reader = csv.DictReader(f)
    for row in reader:
        if fileinput.isfirstline():
            continue
        for key, value in row.items():
            pass #processing

I was hung up on that continue on firstline, because I thought that would
skip the header of the first file. I think now the csv.DictReader(f)
command consumes it first.



More information about the Python-list mailing list