Python reading file? Only reads up to the targeted line. Why? -
my problem program read past targeted line. when new name score input. e.g. txt file contains:
ana,3,6,1,
joe,1,3,
bob,1,
jack,1,1,7,
line in txt file: if name not in line: empty_list.append(lines) #append lines dont have same name elif name in line: s=line.split(',') n= name sc=s[-1] open txt file 'w' #so gets erased , new file updated name can written. write(empty_list) write(n) write(sc)
if input bob , score, want be:
ana,3,6,1,
joe,1,3,
bob,1,2
jack,1,1,7,
but comes out before bob , name updated :( like:
ana,3,6,1,
joe,1,3,
bob,1,2
so jack gets erased.
this should achieve want, given name "bob" , score of 10 be added.
txt_file = "scores.txt" lines = open(txt_file, 'r').readlines() name = "bob" score = 10 open(txt_file, 'w') f: line in lines: if name not in line: f.write(line) #split line, insert new score second last #(the last element '\n') , rejoin string #with commas after casting integers string elif name in line: strings = line.split(',') strings.insert(-1,score) output = ",".join(str(s) s in strings) f.write(output)
in actuality suppose want read information dynamically, sys.argv
friend here.
i think reason code fails (or rather original , not thing posted here) because you're writing empty_list
when there hit, , never again. when reach target line write name , previous one, no new additions empty_list
ever written.
it's not idea write file reading it. if file sufficiently small it's better store data in memory while manipulating it. doing open(txt_file, 'w')
erase old contents of file.
Comments
Post a Comment