导入文本文件,随机播放内容,显示在屏幕上

Import a text file, shuffle the contents, display on screen

我在 txt 文件中有一个团队名称列表。 我想打开列表,打乱名字然后在屏幕上显示结果。已尝试以下代码但收效甚微。

def shuffle2():
    with open("teams.txt", mode="r", encoding="utf-8") as myFile:
        lines = random.shuffle(myFile.readline())
    print(lines)

random.shuffle() 随机播放列表 就地

先将你的台词读入列表,然后随机播放:

def shuffle2():
    with open("teams.txt", mode="r", encoding="utf-8") as myFile:
        lines = list(myFile)
    random.shuffle(lines)
    print(lines)

请注意,这些行将打印为一个长列表;如果您想将它们打印在单独的行上,请使用 *args 调用语法将行作为单独的参数传递给 print(),并将分隔符设置为空字符串:

print(*lines, sep='')

由于 lines 中的每个字符串仍将包含行分隔符 (\n),这将使用这些行分隔符将 lines 的所有内容简单地打印到屏幕上,以确保每个条目都写在自己的行上。

在屏幕上显示之前,您需要打乱所有的行。

import random

with open("teams.txt", mode="r", encoding="utf-8") as myFile:
    lines = myFile.readlines()

random.shuffle(lines)

print (lines)