首页 > 解决方案 > How to align and add space while writing dataframe tocsv in python

问题描述

Just wanted to add space either side to all cell content in DataFrame and needs to be Right aligned. [Input Format Each column with Tab Space][1] [1]: https://i.stack.imgur.com/MM7e0.png

[Output Format with Each column needs to be separated with 5 spaces and right aligned][2] [2]: https://i.stack.imgur.com/unc6B.png

I tried with Str.pad ( its applicable for Strings and prefix applicable only for Headers)

Thanks in advance

标签: python

解决方案


查看numpy.linspace并在此处查看示例。您也可以通过执行以下操作手动执行此操作,例如:

with open(filename, 'r') as f: 
    in_lines = f.readlines()
with open(outfile, 'w') as f:
    eight_spaces = '        '
    for line in in_lines:
        split_line = line.split()
        out_line = eight_spaces.join(split_line)
        f.write(out_line + '\n')

推荐阅读