简体   繁体   English

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

[英]Python - Writing white space to imported CSV data

I want to: 我想要:

  1. Import CSV formatted data into a python list/array 将CSV格式的数据导入python列表/数组

  2. Right justify a 8 space field for the string 右对齐字符串的8个空格字段

  3. Write the output as a text file 将输出写为文本文件

For example, I want to turn csv data such as: 例如,我要打开csv数据,例如:

11111, 22,

333, 4444

Into: 进入:

   11111      22

     333    4444

My code currently looks like: 我的代码当前如下所示:

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)

Thank you 谢谢

I would just rjust each element individually and ''.join them: 我只想rjust每个单独的元素和''.join他们:

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

Or to write it all out: 或全部写出来:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM