在只读脚本上的数据之间添加水平空间

时间:2016-10-02 23:56:16

标签: python readfile

我需要输出看起来不错,看起来很草率。

--------当前输出---------

Below are the players and their scores

John Doe 120
Sally Smooth 115

----------结束当前输出----------

我想要的输出如下

-------所需的输出-----------------

Below are the players and their scores

John Doe         120
Sally Smooth     115

--------结束所需的输出-------------

我当前的代码如下;

def main():

     # opens the "golf.txt" file created in the Golf Player Input python
     # in read-only mode
     infile = open('golf.txt', 'r')

     print("Below are the players and their scores")
     print()

     # reads the player array from the file
     name = infile.readline()

     while name != '':

          # reads the score array from the file
          score = infile.readline()

          # strip newline from field
          name = name.rstrip('\n')
          score = score.rstrip('\n')
          # prints the names and scores
          print(name + " " + score)

          # read the name field of next record
          name = infile.readline()

     # closes the file    
     infile.close()


 main()

2 个答案:

答案 0 :(得分:1)

尝试使用制表符更好地格式化您的空间。

print(name + "\t" + score)

这应该可以让您更接近您想要的输出。但如果某些名称很长,你可能需要使用两个。

答案 1 :(得分:1)

您可以将名称和分数添加到列表中,然后将其作为表格打印为

read_samples

注意:这取决于str.format()

此代码将输出:

erase()