将文件拆分为多个部分并将其设置为variab

2024-05-17 18:13:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文本文件,如下所示:

1,02/09/15,18:00,RNGesus,Ingsoc,Y,Ingsoc
2,03/09/15,18:00,M’lady,Napoleon Wilson,Y,Napoleon Wilson
3,04/09/15,18:00,Ripley,Billy Casper,Y,Billy Casper
4,05/09/15,18:00,Jenkins,Tyler,Y,Jenkins

我需要拆分它们,然后将它们设置为要打印的变量。这是我目前掌握的密码

f = open("fireside.txt", "r")
line = f.readlines()
game=input("Type in your estimate number")
for line in open("fireside.txt"):
    line=line.strip()
    gamenumber, date, time, player1,player2, played, winner= line.split(",")
if gamenumber== game:
    print(gamenumber)
    print(date)
    print(player1)
    print(player2)
    print(played)
    print(winner)

然后我收到了这个错误信息:

ValueError: not enough values to unpack (expected 7, got 1)

如果代码中有任何错误,请编辑它,或者如果有更简单的方法来尝试此任务


Tags: intxtgamedatelineopenjenkinsprint
1条回答
网友
1楼 · 发布于 2024-05-17 18:13:06

打开文件并读取数据两次,使用

f = open("fireside.txt", "r")
line = f.readlines()

以及

for line in open("fireside.txt"):
    line=line.strip()

两种方法都可以,但你应该只做一种。记得关闭你的文件。最好的方法是使用一个文件上下文,在结束时为您关闭它:

with open("fireside.txt") as file:
    for line in file:
        do stuff

相关问题 更多 >