计算目录中多个csv文件中的列数

时间:2018-08-25 06:00:13

标签: python python-3.x python-2.7 pandas csv

我有一个包含大量CSV文件(超过1000个)的目录。我正在使用python pandas库来计算每个CSV文件中的列数。

但是问题在于,某些CSV文件中使用的分隔符不仅"," but "|" and ";"

如何解决此问题:

import pandas as pd
import csv
import os
from collections import OrderedDict

path="C:\\Users\\Username\\Documents\\Sample_Data_August10\\outbound"

files=os.listdir(path)

col_count_dict=OrderedDict() 
for file in files:
    df=pd.read_csv(os.path.join(path,file),error_bad_lines=False,sep=",|;|\|",engine='python')

    col_count_dict[file]=len(df.columns)

我将其存储为字典。

我收到类似以下错误:

Error could possibly be due to quotes being ignored when a multi-char delimiter is used

我用过sep=None,但是没有用。

修改
其中一个csv就是这样Number|CommentText|CreationDate|Detail|EventDate|ProfileLocale_ISO|Event_Number|Message_Number|ProfileInformation_Number|Substitute_UserNo|User_UserNo
第二个是: Number,Description

我无法透露数据。我刚刚给出了列名,因为数据是敏感的。

更新

经过一些调整,并使用打印状态来找出使用andrey-portnoy的代码,我才知道csv嗅探器正在识别“ |”的定界符为“ e”,因此使用if语句将其更改回“ |”。现在它给了我正确的输出。
同样使用read()来代替readline()。在Andrey的答案中的以下代码行中:dialect = csv.Sniffer().sniff(csvfile.read(1024))
但是问题仍然没有解决。经过大量检查,我能够弄清楚这一点,但是每次我可能都不正确地猜测时,这可能会导致错误。
任何帮助都将等待。

1 个答案:

答案 0 :(得分:1)

通过将分隔符指定为sep=",|;|\|",可以使整个字符串成为分隔符。

相反,您想使用csv模块中的Sniffer来检测每个文件(尤其是定界符)中使用的CSV方言。

例如,对于单个文件example.csv

import csv
with open('example.csv', newline='') as csvfile:
    dialect = csv.Sniffer().sniff(csvfile.read(1024))
sep = dialect.delimiter

df = pd.read_csv('example.csv', sep=sep)

默认情况下不要启用Python引擎,因为它慢得多。

相关问题