我有一個函數,它接受d(字典,必須按照ASCII格式排序)和文件名(可能存在也可能不存在的文件)。我必須將確切格式寫入此文件,函數必須返回無。Python文件i/0:錯誤 - 當給定的文件名是字符串時如何寫入文件?
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'
顯然,這意味着我的文件是不是一個文件,它是一個字符串。我該如何解決?
這裏是我目前的功能,它們一起工作來接受字典,對字典進行排序,打開/創建文件進行寫入,將字典以指定格式寫入文件,可以作爲字符串讀取,然後關閉文件:預期產出的
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"
謝謝!這使我可以關閉它。 –