【问题标题】:convert CSV file with one column to ASCII file with multi columns将一列的 CSV 文件转换为多列的 ASCII 文件
【发布时间】:2017-03-06 13:20:28
【问题描述】:

test3.csv 包含一列,包含 33 个数字。我想将一列重塑为 11 行和 3 列。然后,我想将行和列保存为新的 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 文件,比如:

【问题讨论】:

    标签: python csv ascii


    【解决方案1】:

    这里有一些代码可以满足你的需要:

    代码:

    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
    

    【讨论】:

      【解决方案2】:

      我利用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])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-26
        • 2012-08-13
        • 1970-01-01
        • 1970-01-01
        • 2020-03-08
        相关资源
        最近更新 更多