-2

这是我用于读取一个 csv 文件的单个单元格的代码。但是想从csv文件路径所在的.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..
4

3 回答 3

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
于 2013-09-23T09:21:50.697 回答
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
于 2013-09-23T09:21:54.963 回答
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))
于 2013-09-24T09:27:54.917 回答