Skip to main content
 首页 » 编程设计

python之以这种格式将字典导出到文本文件

2024年10月25日9kuangbin


我正在尝试将字典导出到文本文件,如下面的代码所示:

user_scores = {} 
 
with open('Class 1.txt') as f: 
    for line in f: 
        this_line = line.strip().replace("\n","").split(",") 
        user_scores[this_line[0]] = this_line[1:] 
 
    username = "Andy.Singh" 
    score = 25 
 
    user_scores[username] = score 
 
    print(user_scores) 
 
    for user,score in user_scores: 
        f.write(user + ',' + score) 

目前显示的是 Class 1.txt 的文本文件:

Bob.Smith, 10, 20, 30 

这里,字典 user_scores 中写入了 Bob.Smith 的用户名和分数。我也在写另一个新名字,Andy.Singh,他获得了 25 的分数。

当我运行代码时,字典会正确写入字典,如下所示:

{'Andy.Singh': 25, 'Bob.Smith': [' 10', ' 20', ' 30']} 

但最后写入文本文件不起作用。我想写入同一个文件,但这会返回错误:

Traceback (most recent call last): 
  File "/Users/Ahmad/Downloads/Manraj/test.py", line 15, in <module> 
     for user,score in user_scores: 
ValueError: too many values to unpack (expected 2)  

简单来说,我希望文件现在显示:

Bob.Smith, 10, 20, 30 
Andy.Singh, 25 

如何解决这个错误?我是否需要添加我缺少的其他属性?

谢谢。

请您参考如下方法:

您的代码有几处错误。

你得到的错误是因为:

for user,score in user_scores: 

并不像您想象的那样遍历字典的内容。要正确地做到这一点,你需要使用类似的东西:

for user, scores in user_scores.items(): 

其他问题与文件处理有关。默认情况下,open() 只打开一个文件供阅读。要做到这两点,您需要类似 'r+' 的模式,这意味着读取和写入。

另外,在向文件写入行的循环中,需要处理存在分数列表和只有一个分数列表的情况。为了简化事情,我让添加/更新条目总是创建一个值列表,即使该列表只包含一个值。这使得在用于更新文件的 write() 语句中完成的格式化中,只需以一种方式处理分数成为可能——因为它们始终是列表。

user_scores = {} 
 
with open('Class 1.txt', 'r+') as f: 
    # read existing contents 
    for line in f: 
        this_line = [elem.strip() for elem in line.split(",")] 
        user_scores[this_line[0]] = this_line[1:] 
 
    # add or update an entry 
    username = "Andy.Singh" 
    score = 25 
    user_scores.setdefault(username, []).append(str(score)) 
 
    print(user_scores) 
 
    # rewrite file 
    f.seek(0)  # rewind file 
    for user, scores in user_scores.items(): 
        f.write('{}, {}\n'.format(user, ', '.join(s for s in scores))) 

Class 1.txt运行后:

Bob.Smith, 10, 20, 30 
Andy.Singh, 25 

Class 1.txt 将分数加到 30 后再次运行:

Bob.Smith, 10, 20, 30 
Andy.Singh, 25, 30