如何从python中的多个目录中分别读取多个文件

问题描述:

我有x个目录,它们是Star_ {v},v = 0到x。 我在每个目录中有2个csv文件,一个带有“epoch”一词,一个没有。 如果其中一个csv文件有单词“epoch”,它需要通过一组代码发送,否则通过另一个。 我觉得字典是可能的路要走,但此部分代码是有点错乱如何从python中的多个目录中分别读取多个文件

directory_dict={} 

for var in range(0, len(subdirectory)): 
#var refers to the number by which the subdirectories are labelled by Star_0, Star_1 etc. 

    directory_dict['Star_{v}'.format(v=var)]=directory\\Star_{var} 
    #directory_dict['Star_0'], directory_dict['Star_1'] etc. 

    read_csv(f) for f in os.listdir('directory_dict[Star_{var}') if f.endswith(".csv") 
    #reads in all the files in the directories(star{v}) ending in csv. 
    if 'epoch' in open(read_csv[0]).read(): 
    #if the word epoch is in the csv file then it is 
     directory_dict[Star_{var}][read] = csv.reader(read_csv[0]) 
     directory_dict[Star_{var}][read1] = csv.reader(read_csv[1]) 
    else: 
     directory_dict[Star_{var}][read] = csv.reader(read_csv[1]) 
     directory_dict[Star_{var}][read1] = csv.reader(read_csv[0]) 
+0

除了发布无效Python代码的事实之外,这个问题中没有任何问题。 – davidism 2014-12-02 14:58:10

与CSV的问题时,你应该使用csv module,并为您的特定情况下,可以使用一个dictreader并解析头检查你正在寻找

import csv 
import os 

directory = os.path.abspath(os.path.dirname(__file__)) # change this to your directory 
csv_list = [os.path.join(directory, c) for c in os.listdir(directory) if os.path.splitext(c) == 'csv'] 

def parse_csv_file(): 
    " open CSV and check the headers " 
    for c in csv_list: 
    with open(c, mode='r') as open_csv: 
    reader = csv.DictReader(open_csv) 
    if 'epoch' in reader.fieldnames: 
     # do whatever you want here 
    else: 
     # do whatever else 

则列可以从DictReader的CSV头提取出来,并做你想做的

而且你的蟒蛇看起来无效