循环遍历Python目录中的csv文件

时间:2017-11-19 17:38:38

标签: python loops path directory

我正在运行此脚本来遍历CSV文件目录以运行交叉验证。

for filename in os.listdir("/Users/name/PycharmProjects/Project/Data/Nod"):
    k_fold(filename)

我收到错误:

Traceback (most recent call last):
File "/path_of_cross_validation_file", line 28, in <module>
k_fold(filename)
File "/path_of_cross_validation_file", line 7, in k_fold
data = open(myfile).readlines()
IOError: [Errno 2] No such file or directory: 'file_name.csv'

如何遍历所有这些文件以将数据拆分为培训和测试文件?

作为参考,Nod中的文件可能如下所示:

x,y,z
-1.3518261999999999,0.19841946999999999,0.058807577999999999
-1.5427636999999998,0.54079030000000006,-0.15981296
-1.4453497,0.04129998,0.046387657999999998
-1.4743793000000001,-0.064793080000000003,0.18315643000000001

1 个答案:

答案 0 :(得分:1)

事实证明我需要使用glob模块。

以下是解决方案:

for filename in glob.iglob('Path_to_directory/*.csv'):
    k_fold(filename)