将包含一列的CSV文件转换为包含多列的ASCII文件

时间:2017-03-06 13:20:29

标签: python csv ascii

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文件一样:

Image

2 个答案:

答案 0 :(得分:0)

以下是一些可以满足您需求的代码:

<强>代码:

- name: dependency provisioning
  hosts: all
  become: yes
  become_method: sudo
  gather_facts: false
  tasks:
    - name: install python2
      raw: sudo apt-get -y install python-simplejson

- name: production
  hosts: production_host
  roles:
    - nginx
  tasks:
    - name: update apt cache
      apt: update_cache=yes cache_valid_time=3600
  # ....

- name: staging
  hosts: staging_host
  roles:
    - nginx
  tasks:
    - name: update apt cache
      apt: update_cache=yes cache_valid_time=3600
  # ....

测试数据:

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

答案 1 :(得分: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])
相关问题