简体   繁体   中英

making a list from a specific parts of text file

hi I made this little exercise for myself, I want to pull out the last number in each line In this text file which has 5 lines and 6 numbers/line separated by spaces. I made a loop to get all the remaining characters of the selected line starting from the 5th space. it works for every line print(findtext(0 to 3)), except the last line if the last number has less than 3 characters... what is wrong? I can't figure it out

text = open("text","r")
lines = text.readlines()

def findtext(c):
    count = 0
    count2 = 0

    while count < len(lines[c]) and count2<5:
        if lines[c][count] == " ":
            count2=count2+1

        count=count+1

    return float(lines[c][count:len(lines[c])-1])                   

print(findtext(0))

You proposed solution doesn't seem very Pythonic to me.

with open('you_file') as lines:
    for line in lines:
        # Exhaust the iterator
        pass
    # Split by whitespace and get the last element
    *_, last = line.split()
    print(last)

Several things:

  • Access files within context managers, as this guarantees resources are destroyed correctly
  • Don't keep track of indexes if you don't need to, it makes the code harder to read
  • Use split instead of counting the literal whitespace character
with open('file') as f :
    numbers = f.readlines()

last_nums = [ line.split()[-1] for line in numbers ]

line.split() will split the string into elements of a list using the space as a separator (if you put no arguments in it), [-1] will get the last element of this list for you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM