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

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

问题描述

因此:

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')

更新

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

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(":")
    

    这将修复您的错误.

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

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

    1. 真的不知道,为什么要打印逗号.

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

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

    将其更改为以下内容:

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

  • 有一件事,你正在从同一个文件中读取和写入.在这种情况下,如果您需要写入同一个文件,则应该一次读取所有内容.但是,如果您使用单独的文件,则可以使用此代码.

  • 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天全站免登陆