Python - 将空白空间写入导入的CSV数据

时间:2013-01-09 19:33:51

标签: python csv whitespace human-readable

我想:

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

  2. 右对齐字符串

  3. 的8空格字段
  4. 将输出写为文本文件

  5. 例如,我想转换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)
    

    谢谢

1 个答案:

答案 0 :(得分: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)