想要逐个读取多个csv文件,并使用python将文件路径存储在文本文件中

时间:2013-09-23 09:06:46

标签: python csv

这是我的代码,用于读取一个csv文件的单个单元格。但是想从ct文件路径所在的.txt文件中逐个读取多个csv文件。

import csv

ifile = open ("C:\Users\BKA4ABT\Desktop\Test_Specification\RDBI.csv", "rb")

data = list(csv.reader(ifile, delimiter = ';'))
REQ = []
RES = []

n = len(data)
for i in range(n):

    x = data[i][1]
    y = data[i][2]
    REQ.append (x)
    RES.append (y)
    i += 1
for j in range(2,n):
    try:
        if REQ[j] != '' and RES[j]!= '': # ignore blank cell

            print REQ[j], '  ', RES[j]  


    except:
        pass
    j += 1

csv文件路径存储在.txt文件中,如

C:\Desktop\Test_Specification\RDBI.csv

C:\Desktop\Test_Specification\ECUreset.csv
C:\Desktop\Test_Specification\RDTC.csv
and so on..

3 个答案:

答案 0 :(得分:0)

您只需添加一段时间即可读取包含文件列表的文件。第一次公开声明的路径,例如

from __future__ import with_statement

with open("myfile_which_contains_file_path.txt") as f:
    for line in f:
        ifile = open(line, 'rb')
        # here the rest of your code

答案 1 :(得分:0)

您可以将存储在文件中的内容读取到变量中。并且您可以在任何可以使用文字字符串的地方使用带有字符串的变量。所以......

with open('mytxtfile.txt', 'r') as txt_file:
    for line in txt_file:
        file_name = line.strip() # or was it trim()? I keep mixing them up
        ifile = open(file_name, 'rb')
        # ... the rest of your code goes here

也许我们可以解决这个问题......

import csv
with open('mytxtfile.txt', 'r') as txt_file:
    for line in txt_file:
        file_name = line.strip()
        csv_file = csv.reader(open(file_name, 'rb', delimiter=';'))
        for record in csv_file[1:]: # skip header row
            req = record[1]
            res = record[2]
            if len(req + res):
                print req, '   ', res

答案 2 :(得分:0)

您需要使用路径包含\

的原始字符串字符串
import csv

file_list = r"C:\Users\BKA4ABT\Desktop\Test_Specification\RDBI.csv"
with open(file_list) as f:
   for line in f:
       with open(line.strip(), 'rb') as the_file:
           reader = csv.reader(the_file, delimiter=';')
           for row in reader:
               req,res = row[1:3]
               if req and res:
                   print('{0} {1}'.format(req, res))