0

我想要:

  1. 将 CSV 格式的数据导入 python 列表/数组

  2. 右对齐字符串的 8 个空格字段

  3. 将输出写入文本文件

比如我想转csv数据如:

11111, 22,

333, 4444

进入:

   11111      22

     333    4444

我的代码目前看起来像:

import csv

input_file = "csv_file.csv"
my_data = csv.reader(open(input_file, "rb"), delimiter=',')

for i,j in my_data:
    x = ('%-15s %s\n' % (i,j))

with open('my_output.txt', 'w') as file:
    file.writelines(x)

谢谢

4

1 回答 1

1

我会rjust单独每个元素和''.join它们:

''.join(elem.rjust(8) for elem in (i,j))

或者把它全部写出来:

def join_line(line_iter):
    """
    Take a iterable containing strings and right justify each 
    at 8 spaces before joining
    """
    return ''.join(elem.rjust(8) for elem in line_iter)

with open('output','w') as f:
    f.writelines((join_line(row)+'\n') for row in csv_file)
于 2013-01-09T19:37:47.627 回答