如何检查CSV文件的第1行和第2行是否为空?

时间:2019-04-04 07:19:51

标签: python csv

我在特定文件夹中有4个csv文件。我想一一检查每个csv文件的row-1和row-2。如果第一行或第二行为空白,则打印“文件为空”,并同时打印特定的文件名。

path = 'D:/Users/SPate233/Downloads/NS dashboard/sql_query/*.csv'
files = glob.glob(path)
for name in files:
  with open(name) as file:
    reader = csv.reader(file)
    row1 = next(reader)
    print(row1)
    row2 = next(reader)
    print(row2)

错误-

Traceback (most recent call last):
  File "D:\Users\SPate233\Downloads\test.py", line 13, in <module>
    f_row = next(reader)
StopIteration
[Finished in 1.3s with exit code 1]

1 个答案:

答案 0 :(得分:1)

import pandas as pd
path = 'D:/Users/SPate233/Downloads/NS dashboard/sql_query/*.csv'
files = glob.glob(path)
for name in files:
    print(name)
    df = pd.read_csv(name)
    df.info(verbose=True)

如果存在任何空值,它将打印有关您的数据集的信息。df.info()将突出显示数据。