[英]Creating columns with lists read from a file in Python
我目前正在從 Starting Out with Programming Logic & Design, Third Edition 做一個問題:
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
基本上,我的問題是如何在兩個漂亮的列中顯示玩家的姓名和分數。 我輸入的代碼或 output 代碼有問題嗎?
我查看了一堆處理格式化列的答案,一切都比我的目的更復雜。 這是關於計算機編程的介紹 class,所以我需要一個簡單的修復!
請加
print player + " " + score + "\n"
這將解決您的第一個問題。
如果要對字符串進行更多格式化,則字符串具有格式化功能
您正在以簡單格式存儲數據。 如果您使用CSV,那么它很容易閱讀。
首先,寫入文件的代碼應為
# 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()
您可以嘗試這樣的事情:
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()
沒有參數的file.read()方法將讀取文件直到EOF(文件結束),因此在您的示例中, score
將為空字符串,並且player == bob1bill2joe3will4mike5
。 並且最好添加行尾字符('\\ n'),以便您可以遍歷文件的內容。
對於這個問題——讀取文件的正確答案比我最初想的要簡單一些:
file=open('golf.txt','r')
name=True
for line in file:
if name:
print('Name:'+line,end='')
else:
print('Score:'+line)
name = not name
file.close()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.