Search within a file in python -
Search within a file in python -
i working results infra sound detectors have glitches info points recorded '0'. worthless data. want able search file '0', count them , print out result.
all have been able far search file '0' , true/false answer.
this code:
def findzero( fname ): if os.path.isfile(fname): f = open( fname ) s = mmap.mmap(f.fileno(), 0, access=mmap.access_read) if s.find('0') != -1: print 'true' else: print '' return;
scan file line line, counting lines '0'
:
def countzero(fname): try: open(fname) f: homecoming sum(line.strip() == '0' line in f) except ioerror: # not file can read homecoming none
the python bool
type subclass of int
, , true
equal 1, false
0, can sum booleans count.
if needed percentage, need count lines , 0-counts separately:
def count_zeros_and_lines(fname): try: open(fname) f: zeros = total = 0 line in f: if line.strip() == '0': zeros += 1 total += 1 homecoming zeros, total except ioerror: # not file can read homecoming none
this returns count of zeros, , total line count.
python python-2.7
Comments
Post a Comment