【问题标题】:checking if a list in a text file already exists and appending to it检查文本文件中的列表是否已经存在并附加到它
【发布时间】:2016-05-08 03:05:59
【问题描述】:

所以从这里开始:

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

到这里

Lucy: 4,9
Henry: 8,9

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

【问题讨论】:

  • 以附加模式打开文件没有帮助,您将不得不覆盖原始文件。
  • 为什么在 join() 之前打印逗号? file.write(key + ':' + ',' + ',' + ','.join(value))
  • 更容易存储为 json 并进行字典查找

标签: python list append


【解决方案1】:

非常直接的解决方案可能是这样的:(如果您不想使用 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() 用于删除空格和换行符。

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

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

    将其更改为以下内容:

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

【讨论】:

  • 我已经用我的其他代码实现了这个,但它说“对于 dic.iteritems() 中的键、值:NameError: name 'dic' is not defined”
  • 您可能遗漏了一些东西(字典初始化)。代码在我这边运行良好。
  • 什么是字典初始化?对不起,我是新手,我必须导入模块吗?
  • dic.setdefault(key, []).append(value) 将为您节省 if/else 构造。
  • @M.Weiss 你忘了dic = {}这行吗?
【解决方案2】:

解决方案 1:

最好的方法是首先读取字典中的所有数据,最后将其转储到文件中。

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

解决方案 2:

对于每个请求,您必须真正完整的文件,然后重写它。:

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

【讨论】:

  • 但我不确定这是否可行,因为我是从文件中的行中获取数据,而不是从代码中的字典中获取数据?
猜你喜欢
  • 1970-01-01
  • 2013-10-28
  • 2012-08-12
  • 2015-03-26
  • 2021-11-28
  • 1970-01-01
  • 2023-01-25
  • 2014-10-06
  • 2021-06-16
相关资源
最近更新 更多