【问题标题】:Code doesn't save to file代码不保存到文件
【发布时间】:2016-01-30 12:48:27
【问题描述】:

我的代码可以运行但没有将任何内容保存到文本文件中?

def saving_multiple_scores():
    with open(class_number) as file:
          dic = {}
          for line in file:
              key, value = line.strip().split(':')
              dic.setdefault(key, []).append(value)
              file.write(dic)

    with open(class_number, 'a') as file:
        for key, value in dic.items():
            file.write(key + ':' + ','.join(value) + '\n')
            print(dic)

它应该检查名称是否已经在文件中,如果是的话:附加一个分数 如果没有,则使用分数创建一个新列表。

但是,根本没有任何东西可以节省。 Python,IDLE V3.4.2

我是新手,所以感谢任何帮助

【问题讨论】:

  • 尝试在函数定义之外初始化你的字典
  • 不行还是不行
  • 运行前文件是否为空?

标签: python list dictionary


【解决方案1】:

第一个 with 不起作用,因为文件为空,for 循环遍历文件中的行

open(参见https://docs.python.org/2/library/functions.html#open)的默认模式是只读的,因此file.write(dic) 将不起作用

【讨论】:

  • 好的,你建议我做什么来解决这个问题?
  • 很难弄清楚你真正想要做什么
  • 我建议先通过读取文件来创建dict,然后再次打开并从头开始编写
  • 什么意思?你能提供一些代码来证明这一点吗?
【解决方案2】:

扩展 Pawel 的建议,以下是您修复代码的方法:

from collections import defaultdict

def saving_multiple_scores():
    with open(class_number, 'r') as f: # don't use file
          data = defaultdict(list)
          for line in f:
              line = line.strip() 
              if not line:
                  continue # skip over any blank lines in the file
              key, value = line.split(':')
              data[key.strip()].append(value.strip())
              # file.write removed because we don't write in readmode

    with open(class_number, 'a') as f:
        # using 'a' mode will append the score lists
        # to the end of the file
        # to overwrite the file completely, use 'w'
        for key, value in data.items():
            line = '%s:%s\n' % (key, ','.join(value),)
            f.write(line)
            print '%s' % line,

示例输入文件:

alice:1
alice:2
alice:3
bob:1
alice:4
bob:2

示例输出文件:

alice:1
alice:2
alice:3
bob:1
alice:4
bob:2
bob:1,2
alice:1,2,3,4

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-15
    • 2016-05-08
    • 2021-07-15
    • 1970-01-01
    • 1970-01-01
    • 2018-11-12
    • 1970-01-01
    • 2022-01-05
    相关资源
    最近更新 更多