当我读csv时,我想保存指定的行

时间:2015-07-09 23:55:32

标签: python csv

现在,我正在读取指定的列,所以我想读取指定的行
我的代码是:

        colums_001=['A','D']
        f = open("data.csv")
        reader = csv.reader(f)
        headers = None
        for row in reader:
              if not headers:
                    headers = []
                    for j, col in enumerate(row):
                          if col in columns_001:
                                headers.append(j)
              else:
                    result_001.append(tuple([float(row[j]) for j in headers]))

我的csv文件是:

DT   A   B  C  D   
15000 13 24 12 14   
15004 14 15 25 35  
15008 25 24 23 68   
15012 14 12 58 98   
15016 52 45 24 13  

我想阅读并保存:

DT   A   D   
15008 25  68   
15012 14  98  

我该怎么办?

2 个答案:

答案 0 :(得分:0)

将每一行追加到一个数组,然后如果数组中的索引是0或1,则追加到“newFile”。

import csv
file = open('file.csv', 'rU')
csv_file = csv.reader(file)
csvArray = []
newFile = 'newFile.txt'
new_file = open(newFile, 'w+')
for row in csv_file:
    csvArray.append(row)
params = csvArray[0]
for rowInt in range(0, len(csvArray)):
    if rowInt == 0 or rowInt == 1:
        new_file.write(csvArray[rowInt])
newJSON_file.close()

答案 1 :(得分:0)

import csv

columns_001=['A','D']
f = open("data.csv")
reader = csv.reader(f)

# Get the headers and find the indices we want
headers = [i for i in reader.next()[0].split(' ') if i != '']
indices = [i for i in range(len(headers)) if headers[i] in columns_001]

wanted_times = ['15008', '15012']

result_001 = []
for row in reader:
    row = [i for i in row[0].split(' ') if i != '']

    # Get columns of interest and if they are the wanted values of DT
    cols_of_interest = [row[j] for j in indices if row[0] in wanted_times]
    if cols_of_interest:
        # Add DT
        cols = [row[0]]
        cols.extend(cols_of_interest)
        result_001.append(cols)

new_header = ['DT']
new_header.extend(columns_001)

然后你可以把它放在另一个文件或其他东西

print new_header
print result_001

['DT', 'A', 'D']
[['15008', '25', '68'], 
['15012', '14', '98']]