Looping over a text file list with python

后端 未结 5 1457
予麋鹿
予麋鹿 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:28

    Well, I think, you probably want data2 = [word.rstrip("\n") for word in tmp], but without seeing sample input and desired output it's hard to tell.

    Also,

    first[2]=(int(first[2]))
    first[3]=(int(first[3]))
    initialHours = first[2]
    payRate = first[3]
    

    Could be:

    initialHours = int(first[2])
    payRate = int(first[3])
    

    But you'd also need to change other references to first[2]

    Finally, I'd change

    if os.path.isfile(fileQuestion) == True:
    file = open('emps', 'r')
    data = file.readlines()
    for tmp in data:
    

    to:

    if os.path.isfile(fileQuestion) == True:
    with open('emps', 'r') as myfile:
        for tmp in myfile:
    

    This ensures that the file gets closed properly (your code doesn't close it), and iterates directly through the file, rather than using readlines() which needlessly reads the entire file to memory before doing enything else. Note that file is a python builtin, so a bad choice of variable name.

提交回复
热议问题