删除每个字符串后出现的空白行

deh*_*hnm 2 python random

这个程序工作正常,但我在每个玩家后删除空行时遇到问题.我试过用.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)

tim*_*geb 5

您的行read_file包含换行符,然后print默认添加另一行.您可以避免使用第二个换行符print(random.choice(the_line), end='').

其他的建议:

  • read_file.close 什么都不做因为你忘了打电话给方法.
  • 此外,即使这样做read_file.close()也没有意义,因为使用该with语句已经处理了关闭文件.
  • the_line 是一个令人困惑的变量名称,因为它有很多行.
  • 您可能应该将文件读入内存一次(它似乎并不是巨大的),而不是每次random_player调用时都打开并读取它.