这个程序工作正常,但我在每个玩家后删除空行时遇到问题.我试过用.strip但是我得到了错误'list' object has no attribute 'strip'
import random
def random_player(datafile):
with open (datafile, 'r') as read_file:
the_line = read_file.readlines()
print(random.choice(the_line))
random_player(file_name)
random_player(file_name)
random_player(file_name)
random_player(file_name)
random_player(file_name)
Run Code Online (Sandbox Code Playgroud)
我得到了什么:
Toney Douglas
Adonal Foyle
Nate Hawthorne
Joe Stephens
Gary Payton II
Run Code Online (Sandbox Code Playgroud)
我想要的是:
Toney Douglas
Adonal Foyle
Nate Hawthorne
Joe Stephens
Gary Payton II
Run Code Online (Sandbox Code Playgroud)
您的行read_file包含换行符,然后print默认添加另一行.您可以避免使用第二个换行符print(random.choice(the_line), end='').
其他的建议:
read_file.close 什么都不做因为你忘了打电话给方法.read_file.close()也没有意义,因为使用该with语句已经处理了关闭文件.the_line 是一个令人困惑的变量名称,因为它有很多行.random_player调用时都打开并读取它.