python - 检查文本文件中的列表是否已存在并向其追加

标签 python list append

因此:

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

至此

Lucy: 4,9
Henry: 8,9

这个问题现在已经解决了,谢谢

最佳答案

非常直接的解决方案可能是这样的:(如果您不想使用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')

更新

我已经修复了您的代码,您需要更改此行:

  1. 删除以下几行,它们在这里没有用。

    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. 您使用了错误的分隔符。

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

将其更改为以下内容:

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

这将修复您的错误。

注意这里,strip() 用于删除空格和换行符。

  • 不太清楚,为什么要打印逗号。

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

    将其更改为以下内容:

    file.write(key + ':' + ','.join(value) + '\n')
    
  • 有一件事,您正在从同一个文件中读取和写入。在这种情况下,如果需要写入同一个文件,则应该一次读取所有内容。但如果您使用单独的文件,则可以使用此代码。

  • 关于python - 检查文本文件中的列表是否已存在并向其追加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35100461/

    相关文章:

    python - 下载 NLTK 语料库时出现 ElementTree.ParseError

    python - 在Python中仅检索HTTP header 而不检索内容

    Python,通过从较长列表中删除来匹配两个列表长度

    mysql - MySql选择所有记录,并用逗号分隔符显示在单个列中

    jQuery:append() 对象,用delay() 删除它

    node.js - append 到已经存在的文件nodejs?

    python - python 上是否有等效的 kable (R)?

    python - python 中增加数组元素

    jquery - 换行分离 append 按顺序不 append

    python - 将两个一维数组转换为一组元组