Home Ask Login Register

Developers Planet

Your answer is one click away!

A.King February 2016

Python reading file? Only reads up to the targeted line. Why?

My problem is that I would like the program to also read past the targeted line. When a new name with score is input. E.g. the TXT file contains:

Ana,3,6,1,

Joe,1,3,

bob,1,

jack,1,1,7,

 for line in txt file:
     if name not in line:
         empty_list.append(lines)    #Append the lines that dont have the same name
     elif name in line:
     s=line.split(',')
     n= name
     sc=s[-1] 
     open txt file 'w'  #So that everything gets erased and a new file with updated name can be written.
     Write(empty_list)
     write(n)
     write(sc)

If the input is Bob and score, then I want it to be:

Ana,3,6,1,

Joe,1,3,

bob,1,2

jack,1,1,7,

But it comes out with everyone who is before bob and his name updated :( like:

Ana,3,6,1,

Joe,1,3,

bob,1,2

So Jack gets erased.

Answers


Harald Nordgren February 2016

This should achieve what you want, given the name "bob" and a score of 10 be be added.

txt_file = "scores.txt"
lines = open(txt_file, 'r').readlines()

name = "bob"
score = 10

with open(txt_file, 'w') as f:
    for line in lines:

        if name not in line:
            f.write(line)

        #Split the line, insert new score second last
        #(the last element is a '\n') and rejoin the string
        #with commas after casting all integers to string
        elif name in line:
            strings = line.split(',')
            strings.insert(-1,score)
            output = ",".join(str(s) for s in strings)
            f.write(output)

In actuality I suppose you want to read this information dynamically, so sys.argv is your friend here.

I think the reason your code fails (or rather your original and not that thing you posted here) is because you're writing the empty_list when there is a hit, and never again. So when you reach your target line you write that name and all the previous one, but no new additions to empty_list are ever written.

It's generally not a good idea to write to a file as you are reading it. If your file is sufficiently small it's usually better to store the data in memory while manipulating it. Doing open(txt_file, 'w') will erase the old contents of the file.

Post Status

Asked in February 2016
Viewed 1,698 times
Voted 7
Answered 1 times

Search




Leave an answer


Quote of the day: live life