简体   繁体   中英

Check if CSV file is empty or not after reading with DictReader

I'm opening a CSV file and I need to check if the file empty or not, I already know about checking using getsize(). I would like a way by using DictReader. This is my code

infocsv = open('nyfile.csv', 'a')
reader = csv.DictReader(infocsv)

 with open(parafile, "rb") as paracsv: #Read in parameter values as a dictionary paradict = csv.DictReader(paracsv) has_rows = False for line in paradict: has_rows = True if not has_rows: return None 

The number of lines read from the source iterator. This is not the same as the number of records returned, as records can span multiple lines.

Here is an alternative solution:

import csv
with open('nyfile.csv') as infocsv:
    reader = [i for i in csv.DictReader(infocsv)]
    if len(reader)>0:
        print ('not empty')
    else:
        print ('empty')

I tried it on a few CSV files of my own and it works. Let me know if this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM