我正在尝试创建两个程序,一个将数据写入文件golf.txt,第二个程序从golf.txt读取记录并显示它们。当我将输入字段留空时,我试图让程序退出的第一个程序。这是第一个程序的代码。
#Program that reads each player's name and golf score as input
#Save to golf.txt
outfile = open('golf.txt', 'w')
#Enter input, leave blank to quit program
while True:
name = input("Player's name(leave blank to quit):")
score = input("Player's score(leave blank to quit):")
if input ==" ":
break
#write to file golf.txt
outfile.write(name + "\n")
outfile.write(str(score) + "\n")
outfile.close()
使用第二个程序,我无法让程序在一行上显示我想要的输出。这是第二个项目。
#Golf Scores
# main module/function
def main():
# opens the "golf.txt" file created in the Golf Player Input python
# in read-only mode
infile = open('golf.txt', 'r')
# reads the player array from the file
player = infile.read()
# reads the score array from the file
score = infile.read()
# prints the names and scores
print(player + "scored a" + score)
# closes the file
infile.close()
# calls main function
main()
我将非常感谢您提供的任何帮助或建议。
答案 0 :(得分:1)
两个主要问题:
1。)你的第一个代码有if input == ' '
,这在两个方面有误:
input
是一个功能。您已保存输入,因此您应该与name
和score
进行比较。
input
会返回''
。
所以改为:' '
甚至是if name == '' or score == '':
(做同样的事情)
2。)if '' in (name,score):
将自动将文件中的所有内容读作一个字符串。您希望将其拆分为每个组件,以便您可以执行以下操作:
file.read()
或
player,score = file.readlines()[:2]
然后打印(中间字符串中有前导和尾随空格!)
player = file.readline()
score = file.readline()
答案 1 :(得分:1)
让两个程序都正常工作
计划1:
#Program that reads each player's name and golf score as input
#Save to golf.txt
outfile = open('golf.txt', 'w')
#Enter input, leave blank to quit program
while True:
name = input("Player's name(leave blank to quit):")
if name == "":
break
score = input("Player's score:")
#write to file golf.txt
outfile.write(name + "\n")
outfile.write(str(score) + "\n")
outfile.close()
计划2:
#Golf Scores
# main module/function
def main():
# opens the "golf.txt" file created in the Golf Player Input python
# in read-only mode
infile = open('golf.txt', 'r')
# 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 + " scored a " + score)
# read the name field of next record
name = infile.readline()
# closes the file
infile.close()
# calls main function
main()
答案 2 :(得分:0)
在检查之前消除input
的空格(我会使用.strip()
方法)。并将其与空字符串""
进行比较,而不是空格" "
。
答案 3 :(得分:0)
使用“while true”区块,你不断询问并取名字和分数,但是你会覆盖它们,所以你总是只有最后一对。
您需要保留所有内容,以便列出清单:
names_and_scores = []
while True:
name = input("Player's name(leave blank to quit):").strip()
if name == "":
break
score = input("Player's score:").strip()
if name != "" and score != "":
names_and_scores.append("{}; {}".format(name, score))
with open('golf.txt', 'w') as outfile:
outfile.write("\n".join(names_and_scores))
第二个程序打开文件,逐行读取,拆分并打印:
with open('golf.txt', 'r') as infile:
for line in infile:
name, score = line.strip().split("; ")
print("{} scored a {}.".format(name, score))