【问题标题】:How can I use read_csv for each csv files even if it is empty ? Python Pandas即使每个 csv 文件为空,如何使用 read_csv ?蟒蛇熊猫
【发布时间】:2021-02-03 13:43:00
【问题描述】:

我有这段代码可以尝试为每个 csv 文件执行这个程序:

import pandas as pd
import os

directory_path_csv = r'CSV_Files'

for file in os.listdir(directory_path_csv):
    if file.endswith(".csv"):
        filename = file
        df = pd.read_csv(filename, usecols= ['date','time', 'toto','tata'], parse_dates=[['date', 'time']])

但我有这个错误:FileNotFoundError: [Errno 2] File File1.csv does not exist: 'File.csv' 不明白为什么?在 csv 文件夹中,我可以拥有没有数据的 csv 文件,只有列的名称。

感谢您的宝贵时间!

【问题讨论】:

  • 你的file在文件夹directory_path_csv中,所以你需要做os.path.join(directory_path_csv, file)
  • @JustinEzequiel 我可以读取 csv 文件,但是当程序只用一行(列名)执行某个文件时,因为它无法完成其余的工作,程序停止而不做其余的工作
  • 您的错误消息(FileNotFoundError: [Errno 2] 文件 File1.csv 不存在:'File.csv')与您的声明不符。

标签: python pandas dataframe


【解决方案1】:
# necessary imports
import pandas as pd
import glob

假设您有一些非空的 csv:

for x in range(10):
    pd.DataFrame(['exampleDf'+repr(x)]).to_csv('nonempty'+repr(x)+'.csv')

还有一个空的:

# this is a shell command:
touch empty.csv

将所有 csv 文件名放到一个列表中

csvs=glob.glob('*csv')

你可以通过它们循环捕捉EmptyDataErrors

for csv in csvs:
    try:
        pd.read_csv(csv)
    except pd.errors.EmptyDataError:
        pass # or do whatever you want with empty csvs

编辑:如果 csv 有标题但没有数据

如果某些 csv 有标头但没有数据,则某些 csv 也有数据。重现情景:

for x in range(10):
    pd.DataFrame({'header':[1,2]}).to_csv('nonempty'+repr(x)+'.csv')
for x in range(10):
    pd.DataFrame({'header':[]}).to_csv('empty'+repr(x)+'.csv')

然后可以做:

csvs=glob.glob('*csv')
for csv in csvs:
    df = pd.read_csv(csv)
    if len(df.index)>0:
        # then df is non-empty, do whatever with it
        print(df)
    else:
        # then df is empty
        print(df)

【讨论】:

  • 谢谢,我把read_csv 和我的治疗放在try 部分但是当程序读取另一个csv文件时,第一行是我的df列的名称,所以它通过了try 部分不在 except 部分
  • 所以你的 csv 不是完全空的,它有列名,但没有数据?
  • 没错!造成误会请见谅
猜你喜欢
  • 2021-11-09
  • 2022-10-06
  • 2022-11-14
  • 2016-10-16
  • 1970-01-01
  • 2018-08-20
  • 2022-01-11
  • 2021-02-18
  • 1970-01-01
相关资源
最近更新 更多