使用Python中的文件创建列表

时间:2013-10-25 06:17:40

标签: python list

我目前正在开始使用编程逻辑& amp;设计,第三版:

  

Springfork业余高尔夫俱乐部每周末举办一场锦标赛。该俱乐部   总统要求你设计两个项目。   (1)将每个球员的名字和高尔夫比分作为键盘读取的程序   输入,然后将这些记录保存在名为golf.dat的文件中。 (每条记录   将有一个球员名称的字段和一个球员得分的字段。)   (2)从golf.dat文件中读取记录并显示它们的程序。

我已经创建了第一个没问题。第二个我遇到麻烦了。这是我的代码:

    # main module/function
def main():

        # opens the "golf.txt" file created in the Golf Player Input python
        # in read-only mode
    inGolf = open('golf.txt', 'r')
        # reads the player array from the file
    player = inGolf.read()
        # reads the score array from the file
    score = inGolf.read()
        # prints the names and scores

    print player + "   " + score

        # closes the file    
    inGolf.close()

    # calls main function
main()

我在显示玩家姓名和分数方面遇到了麻烦。我的方式显示如下:

bob1bill2joe3will4mike5 

我的第一个程序中的列表代码是:

        # loop to get names and scores, both of which are saved in array
counter = 0
while counter < numPlayers:
        # gets the players' names
    player[counter] = raw_input("Please enter the player's name.")
        # writes the names to the file
    outGolf.write(player[counter] )
        # gets the players' scores
    score[counter] = input("Please enter that player's score.")
        # writes the scores to the file
    outGolf.write(str(score[counter]) )
    counter = counter + 1

基本上,我的问题是如何在两个不错的专栏中显示球员的名字和分数。我输入代码或输出代码有问题吗?

我查看了一堆处理格式化列的答案,一切都比我的目的更复杂。这是对计算机编程类的介绍,所以我需要一个简单的修复方法!

4 个答案:

答案 0 :(得分:0)

请添加

print player + "   " + score + "\n"

这将解决您的第一个问题。

如果要在字符串中进行更多格式化,则String具有格式化功能

String Formatting Operations

您以简单格式存储数据。如果您使用CSV,那么它将很容易阅读。

答案 1 :(得分:0)

首先,写入文件的代码应为

# loop to get names and scores, both of which are saved in array
counter = 0
while counter < numPlayers:
    # gets the players' names
    player = raw_input("Please enter the player's name.")
    # gets the players' scores
    score = input("Please enter that player's score.")

    # Write the scores to the file in a comma-separated format
    outGolf.write(player+','+score+'\n')
    counter = counter + 1

然后,当你想做一个漂亮的展示

# main module/function
def main():
    # opens the "golf.txt" file created in the Golf Player Input python
    # in read-only mode
    inGolf = open('golf.txt', 'r')
    # reads the player array from the file
    allRecords = inGolf.readlines()
    # print the data
    for record in allRecords:
        player = record.split(',')[0]
        score = record.split(',')[1]

        print player + "\t" + score + "\n"

    # closes the file    
inGolf.close()

# calls main function
main()

答案 2 :(得分:0)

您可以尝试这样的事情:

def main():
    inGolf = open('golf.txt', 'r')
    names = [] # to store names
    scores = [] # to store scores
    for line in inGolf: # reads file line by line
        line_list = line.split(",") # list formed by each word (separated by comma) 
        names.append(line_list[0]) # append to respective list
        scores.append(line_list[1])

    for i in range(len(names)): # printing
        print "{0:20}{1:10}".format(names[i], scores[i]) # 20 and 10 are the field length

    inGolf.close()

def w(numPlayers): # to write the file
    counter = 0
    outGolf = open('golf.txt', 'w')
    while counter < numPlayers:
        name = raw_input("Please enter the player's name:")
        outGolf.write(name + ",") # separate name and score by a comma
        score = input("Please enter that player's score:")
        outGolf.write(str(score) + "\n") # just add a "\n" to write in different line next time
        counter = counter + 1
    outGolf.close()

w(2)
main()

答案 3 :(得分:0)

没有参数的file.read()方法将文件读取到EOF(文件末尾),因此在您的考试中,score将为空字符串和player == bob1bill2joe3will4mike5。并且最好添加行尾字符('\ n'),以便您可以迭代文件的内容。