Python file i/0: error -- 当给定的文件名是字符串时如何写入文件?

Python file i/0: error -- How to write to a file when the filename given is a string?

我有一个函数接受 d(必须按键按顺序排序的字典)和文件名(可能存在也可能不存在的文件。)我必须将确切的格式写入此文件,并且该函数必须 return None。

Format: Every key-value pair of the dictionary should be output as: a string that starts with key, followed by ":", a tab, then the integers from the value list. Every integer should be followed by a "," and a tab except for the very last one, which should be followed by a newline.

问题是当我关闭文件和 运行 我的测试人员时,它告诉我这个错误:

'str' object has no attribute 'close'

显然这意味着我的文件不是一个文件,它是一个字符串。我该如何解决?

这是我目前的功能,它们一起工作接受字典,排序字典,open/create文件写入,将字典以指定格式写入文件,可以作为字符串读取,然后关闭文件:

def format_item(key,value):
    return key+ ":\t"+",\t".join(str(x) for x in value)
def format_dict(d):
    return sorted(format_item(key,value) for key, value in d.items())
def store(d,filename):
    with open(filename, 'w') as f: 
        f.write("\n".join(format(dict(d))))
    filename.close()
    return None

预期输出示例:

IN: d = {'orange':[1,3],'apple':[2]}" OUT: store(d,"out.txt") the file contents should be read as this string: "apple:\t2\norange:\t1,\t3\n"

您实际上已将文件句柄设置为 f 但您正试图关闭文件名。

所以你的关闭命令应该是 f.close()