[Tutor] How parse files in function of number of lines

Dave Angel davea at davea.name
Thu May 29 09:07:11 CEST 2014


"jarod_v6 at libero.it" <jarod_v6 at libero.it> Wrote in message:
> Dear all!
> I have two example files:
> tmp.csv:
> name	value	root
> mark	34	yes
> 
> tmp2.csv
> name	value	root
> 
> 
> I want to print a different text if I have more than one row and if I have 
> only one row. My code is this:
> with open("tmp.csv") as p:
>     header =p.next()
>     for i in p:
>         print i
>         g = ()
>     if not g:
>             print  header
> mark	34	yes
> 
> no
> 
> I want to obtain only where I have only the header the header string? How can 
> I do this?Thnks for your great patience and help!
> 

The most straightforward way is to define a flag that starts
 False, and becomes True if there are any lines after the header.
 

has_body = False
for line in infile:
    print line
    has_body = True

if has_body:
    print header
else:
    print "something else"



-- 
DaveA



More information about the Tutor mailing list