检查是否在一个文本文件的列表已经存在,并追加到它 [英] checking if a list in a text file already exists and appending to it

查看:251
本文介绍了检查是否在一个文本文件的列表已经存在,并追加到它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以从这个:

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

要这个

Lucy: 4,9
Henry: 8,9

这是现在固定谢谢

推荐答案

非常简单的解决方案可能是这样的:(如果你不希望使用defaultdict)

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

我有固定的code,你需要改变这一行:

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


  1. 删除以下行,他们是无用的在这里。

  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


  • 您使用了错误的分隔符。

  • You are using the wrong delimiter.

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


  • 此更改如下:

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

    这将解决您的错误。

    N.B。在这里,带()是那里删除空格和换行。

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

    真的不知道,你为什么prining逗号。

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

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

    此更改如下:

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


  • 一件事,你正在阅读,并从同一个文件写入。在这种情况下,如果你需要写同一个文件,你应该阅读的一次。但是如果你使用一个单独的文件,你只是这个code罚款。

  • 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.

    这篇关于检查是否在一个文本文件的列表已经存在,并追加到它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆