@@ -38,7 +38,7 @@ def read_file_format(fpath):
3838
3939
4040def parse_lines (lines , spec , strip = True , type_errors = 'raise' , encoding = 'utf-8' ,
41- src_file = None ):
41+ src_file = None , skip_blank_lines = False ):
4242 """Parse iterable of lines of fixed width data."""
4343
4444 fieldstruct = struct .Struct (
@@ -50,6 +50,9 @@ def parse_lines(lines, spec, strip=True, type_errors='raise', encoding='utf-8',
5050
5151 for idx , line in enumerate (lines , start = 1 ):
5252
53+ if skip_blank_lines and len (line .rstrip (b'\r \n ' )) == 0 :
54+ continue
55+
5356 data = fieldstruct .unpack_from (line )
5457 data = tuple (
5558 s .decode (encoding ).strip () if strip else s .decode (encoding ) for s in data
@@ -83,15 +86,18 @@ def parse_lines(lines, spec, strip=True, type_errors='raise', encoding='utf-8',
8386 yield OrderedDict (zip (colnames , values ))
8487
8588
86- def parse_file (fpath , spec , strip = True , type_errors = 'raise' , encoding = 'ascii' ):
89+ def parse_file (fpath , spec , strip = True , type_errors = 'raise' , encoding = 'ascii' ,
90+ skip_blank_lines = False ):
8791 """Read data from fixed width file."""
8892
8993 with open (fpath , 'rb' ) as fh :
90- yield from parse_lines (fh , spec , strip , type_errors , encoding , src_file = fpath )
94+ yield from parse_lines (
95+ fh , spec , strip , type_errors , encoding , fpath , skip_blank_lines
96+ )
9197
9298
9399class DictReader :
94- def __init__ (self , f , fieldinfo ):
100+ def __init__ (self , f , fieldinfo , skip_blank_lines = False ):
95101
96102 try :
97103 if os .path .isfile (fieldinfo ):
@@ -107,7 +113,9 @@ def __init__(self, f, fieldinfo):
107113 self ._f = f
108114 self .line_num = 0
109115 self .fieldnames = tuple (n for w , t , n in self ._spec )
110- self ._records = parse_lines (self ._f , self ._spec )
116+ self ._records = parse_lines (
117+ self ._f , self ._spec , skip_blank_lines = skip_blank_lines
118+ )
111119
112120 def __iter__ (self ):
113121 return self
0 commit comments