使用Python从目录中读取所有csv文件

使用Python从目录中读取所有csv文件

本文介绍了使用Python从目录中读取所有csv文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望这不是小事,但我想知道以下几点:

I hope this is not trivial but I am wondering the following:

如果我有一个包含 n csv个文件的特定文件夹,我该如何一次一次地迭代读取所有文件,并对它们的值进行一些计算?

If I have a specific folder with n csv files, how could I iteratively read all of them, one at a time, and perform some calculations on their values?

例如,对于单个文件,我做类似的事情,并在x数组上执行一些计算:

For a single file, for example, I do something like this and perform some calculations on the x array:

import csv
import os

directoryPath=raw_input('Directory path for native csv file: ')
csvfile = numpy.genfromtxt(directoryPath, delimiter=",")
x=csvfile[:,2] #Creates the array that will undergo a set of calculations

我知道我可以检查给定文件夹中有多少csv个文件(请检查):

I know that I can check how many csv files there are in a given folder (check here):

import glob
for files in glob.glob("*.csv"):
    print files

但是我没有弄清楚如何将numpy.genfromtxt()函数嵌套在for循环中,因此我只能读取由我指定的目录的所有csv文件.

But I failed to figure out how to possibly nest the numpy.genfromtxt() function in a for loop, so that I read in all the csv files of a directory that it is up to me to specify.

编辑

我的文件夹中只有jpgcsv文件.后者的名称为eventX.csv,其中 X 的范围是1到50.因此,我所指的for循环应按原样考虑文件名.

The folder I have only has jpg and csv files. The latter are named eventX.csv, where X ranges from 1 to 50. The for loop I am referring to should therefore consider the file names the way they are.

推荐答案

我就是这样做的:

import os

directory = os.path.join("c:\\","path")
for root,dirs,files in os.walk(directory):
    for file in files:
       if file.endswith(".csv"):
           f=open(file, 'r')
           #  perform calculation
           f.close()

这篇关于使用Python从目录中读取所有csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 08:34