检查文本文件中的列表是否已经存在并附加到它

编程入门 行业动态 更新时间:2024-10-16 20:27:45
本文介绍了检查文本文件中的列表是否已经存在并附加到它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

因此:

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:

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

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.

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

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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-17 20:05:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/921501.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文本文件   到它   列表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!