Python。如何阅读多个.csv文件?

问题描述:

我有超过200个.csv文件,我想在同一时间(当前和下一个)读取和计算它们中的两个。我试图用水珠大熊猫数据帧Python。如何阅读多个.csv文件?

import glob 

for file in glob.glob(path+'*.csv'): 
    x1 = pd.read_csv(file, delimiter=',', dtype=None, names=('x', 'y')) 
    x2 = pd.read_csv(file + 1 , delimiter=',', dtype=None, names=('x', 'y')) 

我没有其他想法。

+0

以前和下一个?那没有意义。你的意思是:***当前***和下一个?或***当前***和前一个? – Abdou

+0

@Abdou你是对的 - **目前的**是我想用的单词;-) – ruan

如果你想与在每次迭代的当前和下一个文件的工作,下面应该做的:

from glob import glob 


files = glob('*.csv') 

for i, file in enumerate(files[:-1]): 
    x1 = pd.read_csv(file, delimiter=',', dtype=None, names=('x', 'y')) 
    x2 = pd.read_csv(files[i+1] , delimiter=',', dtype=None, names=('x', 'y')) 
    # Do what you want to do 

这使用enumerate跟踪从files序列当前文件的索引。通过这种方式,您可以在处理“当前”文件时抓住“下一个文件”,只需添加1当前索引。

我希望这会有所帮助。

可以使用pairwise配方从itertools文档:

from itertools import tee 
def pairwise(iterable): 
    "s -> (s0,s1), (s1,s2), (s2, s3), ..." 
    a, b = tee(iterable) 
    next(b, None) 
    return zip(a, b) 

来源:https://docs.python.org/3/library/itertools.html#itertools-recipes

与用法:

for file1, file2 in pairwise(glob.glob(path+'*.csv')): 
    ...