使用
csv模块:
import csv...with open(in_fnam) as in_file: with open(out_fnam, 'w') as out_file: writer = csv.writer(out_file) for row in csv.reader(in_file): if row: writer.writerow(row)
如果还需要删除所有字段为空的行,请将行更改
if row:为:
if any(row):
而且,如果您还想将仅包含空格的字段视为空白,则可以将其替换为:
if any(field.strip() for field in row):
请注意,在Python 2.x和更早版本中,该
csv模块需要二进制文件,因此您需要使用e
'b'标志打开文件。在3.x中,这样做将导致错误。



