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

时间:2017-03-07 16:10:20

标签: python text-files

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

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)

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

1 个答案:

答案 0 :(得分:0)

您正在打开文件并使用

两次读取数据
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