【问题标题】:Writing to a text file Python [duplicate]写入文本文件Python [重复]
【发布时间】:2012-12-16 19:33:40
【问题描述】:

可能重复:
Writing nicely formatted text in Python

我有这段代码用于将标题写入创建的 txt 文件:

if not os.path.exists('list.txt'):
    f= file('list.txt', 'w')
    f.write ("\t".join("".join (str(row)) for row in header_names.keys()))+"\n")
    f.write ("\n")

这是我用来将新行附加到文本文件的代码:

f = open("list.txt","a")

f.write ("\t".join("".join (str(row)) for row in header_names.values()))+"\n")
f.write ("\n")
f.close()

在文本文件中写入的输出不是我想要的:

Name    some number some number2    % percentage    average
Test    2   2   100.0   0.4
TestTestTest    3   4   75.0    0.49
tes 2   3   66.67   0.33

我想要这样的东西:

Name           some number  some number2    % percentage    average
Test           2            2               100.0           0.4
Test           2            2               100.0           0.4
TestTestTest   3            4               75.0            0.49
tes            2            3               66.67           0.33

有没有什么简单的方法可以做到这一点。它不是强制性的,它是这样写入txt的,但是读取的输出应该......

【问题讨论】:

  • 使用格式字符串 "%-6s" 将为您提供 6 的文本宽度,其中文本右对齐...或者左对齐...
  • 使用制表符? (\t)

标签: python arrays printing


【解决方案1】:

将每一列格式化为一定的宽度,例如:

>>> header = ['one', 'two', 'three']
>>> print [format(el, '<30') for el in header]
['one                           ', 'two                           ', 'three                         ']
>>> print ''.join(format(el, '<30') for el in header)
one                           two                           three                         

【讨论】:

  • @user1509923 查看this doc page 的“对齐文本并指定宽度:”部分以查看不同的格式示例。
  • 谢谢,我每天都在学习新东西:D
猜你喜欢
  • 1970-01-01
  • 2018-02-02
  • 2011-06-10
  • 1970-01-01
  • 2016-08-01
  • 1970-01-01
  • 2015-02-13
  • 2016-02-15
  • 2016-12-07
相关资源
最近更新 更多