將輸出寫入'example.txt'
,開始與此:
with open('example.txt', 'w') as out_file:
out_file.write(' ... whatever you want to write to the file ...\n')
要加入分類key, dict[key]
串入行,這樣做:
'\n'.join(['%s, %s' % item for item in sorted(dict.items())])
如果這對你來說太複雜了,做這個:
for (key, value) in sorted(dict.items()):
out_file.write('%s %s\n' % (key, value))
全部放在一起:
def pretty_print(dict):
with open('example.txt', 'w') as out_file:
for (key, value) in sorted(dict.items()):
out_file.write('%s %s\n' % (key, value))
h = { 'a': 1, 'b': 2 }
pretty_print(h)
你如何使用它看,它好像你叫'file'意味着是一個Python'dict'參數。你能否更具體地瞭解你需要完成什麼? – chucksmash
就像當我使用這個,我只是可以打印一個特定的字符串。但我想應用這個文件,如infile = open(file,'r'),outfile = open('example.txt','w') 。我想從用戶文件打印新文件的功能。 –
你想要輸出到一個新的文件到底是什麼? –