读取多个CSV文件,在空行处剪切,对列进行排序

时间:2017-04-07 12:51:16

标签: python arrays csv

我想用python 3.6读取多个CSV文件,跳过标题并停在第一个空行。然后我想只提取每个csv文件的第四列填充到一个数组,但排序如下所示。

我的档案:CSV Files

到目前为止,这是我的代码,但我对输出顺序不满意,也许有更优雅的方式?

import { ResponseContentType } from '@angular/http';

exportInternalOrder(body) {
    let user_token: string = this.sessionService.getToken();
    let headers = new Headers();
    headers.append('Authorization', 'Bearer ' + user_token);
    return this.http.post(this.config.exportInternalOrder, body,{
        headers: headers,
        responseType: ResponseContentType.Blob
    }).map(res => new Blob([res._body],{ type: 'application/vnd.ms-excel' }));
}

我的输出是:csvdata_d = [' 1.1',' 1.2',' 1.3',' 2.1', ' 2.2',' 2.3',' 3.1',' 3.2',' 3.3']

但我希望它是[[' 1.1',' 2.1',' 3.1'],[' 1.2&# 39;,' 2.2'' 3.2'],[' 1.3'' 2.3'' 3.3 ']]

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

我用numpys genfromtxt模块和一个循环来解决它,找到空行

headsize=2 #lines toskip at beginning
csvdata=[]
measuredata=[]

with open (csvname[0])as f: #Measurement of file to first empty row
    reader = csv.reader(f)
    readerlist=list(reader)
    lengthfile=(len(readerlist))
    for row in readerlist[headsize:]:
        if len(row)== 0:
            break
        else:
          measuredata.append(list(row[3]))  

skfooter=int(lengthfile-(len(measuredata)+(Headsize+1))) #calc number of rows below empty line

for i in range(timestep):
    data=np.genfromtxt((csvname[i]), delimiter=',', skip_header=headsize,   usecols=3, skip_footer=skfooter)
    csvdata.append(data)


s=[]
for i in range (len(csvdata[0])):
    s.append([item[i] for item in csvdata])    
print(s)