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

时间:2014-12-02 14:48:51

标签: python csv dictionary directory multiple-files

我有x个目录是Star_ {v},其中v = 0到x。 我在每个目录中有2个csv文件,一个带有" epoch",一个没有。 如果其中一个csv文件有单词" epoch"在它中需要通过一组代码发送,否则通过另一组代码发送。 我认为字典可能是要走的路,但代码的这一部分有点混乱

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])

1 个答案:

答案 0 :(得分: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标题中提取它并做你想做的事情

你的python也看起来无效