2014-12-02 103 views
-1

我有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

回答

0

與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頭提取出來,並做你想做的

而且你的蟒蛇看起來無效

相關問題