我想:
将CSV格式的数据导入python列表/数组
右对齐字符串
将输出写为文本文件
例如,我想转换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)
谢谢
答案 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)