2017-03-06 136 views
1

test3.csv包含一列有33個數字的列。我想將這一列重新塑造成11行3列。然後,我想將新的ascii文件保存爲附加圖像的行和列。將帶有一列的CSV文件轉換爲帶有多列的ASCII文件

首先嚐試:

import csv 
f = open('test3.csv') 
csv_f = csv.reader(f) 
for row in csv_f: 
    print row /* The result is 

結果是:

['0.000016'] ['0.000045'] ['0.000062'] ['0.000063'] ['0.000063'] ['0.000063']... **[' ']** means string? 

第二個嘗試:

f = open('test3.csv') 
csv_f = csv.reader(f) 
for row in csv_f: 
    print row[0] 

結果是:

0.000016 0.000045 0.000062 0.000063 0.000063 0.000063 ...I think they are number. 

第三次嘗試:

import csv 
import numpy as np 
f = open('test3.csv') 
csv_f = csv.reader(f) 
a1 = [] 
for row in csv_f: 
    a1.append(row[0]) 
print a1 

結果是:

['0.000016', '0.000045', '0.000062', '0.000063', '0.000063', '0.000063',...]. 

其實我想這個結果像ASCII文件:

Image

回答

0

下面是一些代碼,會做你需要的東西:

代碼:

import csv 

# read each line of the input csv 
with open('file3') as f: 
    csv_f = csv.reader(f) 

    # convert the first element of each line to a formated float 
    numbers = ['%.6f' % float(row[0]) for row in csv_f] 

# make sure the length is divisible by 3 
numbers += [''] * (-len(numbers) % 3) 

# reorder to by 3 
numbers = [(numbers[i], numbers[i+1], numbers[i+2]) 
      for i in range(0, len(numbers), 3)] 

# print each line 
for line in numbers: 
    print(' '.join(line)) 

測試數據:

0.000016 
0.000045 
0.000062 
0.000063 
0.000063 
0.000063 
0.000079 
0.000078 
0.000045 
0.000062 
0.000062 
0.000062 
0.000062 
0.000062 
0.000062 
0.000077 
0.000073 
0.000062 
0.000062 
0.000045 
0.000063 

結果:

0.000016 0.000045 0.000062 
0.000063 0.000063 0.000063 
0.000079 0.000078 0.000045 
0.000062 0.000062 0.000062 
0.000062 0.000062 0.000062 
0.000077 0.000073 0.000062 
0.000062 0.000045 0.000063 
0

我利用this great answer

from itertools import izip_longest 

def grouper(iterable, n, fillvalue=None): 
    args = [iter(iterable)] * n 
    return izip_longest(*args, fillvalue=fillvalue) 

with open('data.txt', 'r') as f: 
    for group in grouper(f, 3, ''): 
     print ' '.join([x.strip() for x in group]) 
相關問題