Looping over a text file list with python

后端 未结 5 1399
予麋鹿
予麋鹿 2021-01-29 10:16

EDIT: Have updated post for better clarity, no answers have yet to help!

Alright, so my assignment is to take a text file, that would have 4 entries per line, those bein

5条回答
  •  一个人的身影
    2021-01-29 10:36

    You are using these lines:

    data = file.readlines()
    for tmp in data:
    

    which already splits your data into lines, and iterates through them. That means that this line [data2= [word.rstrip("\n") for word in data]] is setting data2 to be the first line EVERY TIME, which renders the original for loop useless.

    Try instead:

    tmp = tmp.split()
    

    which will split each line as you iterate, you can now call tmp as a list, like you called first except it will reflect the values for each line.

    You could also change your original for loop to:

    for tmp in file:
    

    since file objects in python are generators that yield each line (this saves you some memory space)

提交回复
热议问题