checking if a list in a text file already exists a

2019-08-14 19:33发布

问题:

So from this:

Lucy:4
Henry:8
Henry:9
Lucy:9

To this

Lucy: 4,9
Henry: 8,9

this is now fixed thank you

回答1:

Very straight forward solution might be like this: (If you don't want to use defaultdict)

with open('input.txt') as f:
    dic = {}
    for line in f:
        key,value = line.strip().split(':')
        dic.setdefault(key,[]).append(value)

with open('output','a') as f:
    for key,value in dic.items():
        f.write(key + ':' + ','.join(value) + '\n')

UPDATE

I have fixed your code, and you need to change this lines:

  1. Remove the following lines, they are useless here.

    file = open(class_number, 'a') #opens the file in 'append' mode so you don't delete all the information
    file.write(str(name + ",")) #writes the name and ":" to file
    file.write(str(score)) #writes the score to file
    file.write('\n')#writes the score to the file
    file.close()#safely closes the file to save the information
    
  2. You are using the wrong delimiter.

    key,value= line.split(",")
    

Change this to below:

    key,value= line.strip().split(":")

This will fix your error.

N.B. Here, strip() is there to remove spaces and newlines.

  1. Don't really know, why you are prining the commas.

    file.write(key + ':' + ',' + ',' + ','.join(value))
    

    Change this to below:

    file.write(key + ':' + ','.join(value) + '\n')
    
  2. One thing, you are reading and writing from the same file. In that case, you should read all at once if you need to write to the same file. But if you use a separate file, you are just fine with this code.



回答2:

Solution 1:

Best way to do so is first read all data in dictionary and finally dump it to file.

from collections import defaultdict

result = defaultdict(list)

def add_item(classname,source):    
    for name,score in source:
        result[name].append(score)
    with open(classname,'w') as c:
        for key,val in result.items():
            c.write('{}: {}'.format(key,','.join(val))

Solution 2:

for each request, you have to real whole the file and then rewrite it.:

def add_item(classname,name,score):
    result={item.spilt(':')[0],item.spilt(':')[1] for item in open(classname,'r').readlines()]
    result[name].append(score)
    with open(classname,'w') as c:
            for key,val in result.items():
                c.write('{}: {}'.format(key,','.join(val))