2015-09-07 82 views
0

我有一個像這樣的函數來將用戶文件{'a':1,'b':2}打印到像abc.txt這樣的新文件,但我不知道如何正確添加infile和outfile。有人能幫我嗎?如果我想替換for循環以使其更簡單,我該怎麼做?將散列打印到文件

def pretty_printing(dict): 

     order_keys = dict.keys() 
     order_keys.sort() 

     for key in order_keys: 
      print key, dict[key] 
+0

你如何使用它看,它好像你叫'file'意味着是一個Python'dict'參數。你能否更具體地瞭解你需要完成什麼? – chucksmash

+0

就像當我使用這個,我只是可以打印一個特定的字符串。但我想應用這個文件,如infile = open(file,'r'),outfile = open('example.txt','w') 。我想從用戶文件打印新文件的功能。 –

+0

你想要輸出到一個新的文件到底是什麼? –

回答

0

將輸出寫入'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) 
+0

我們可以用更簡單的方式因爲我只是個新手而已。這段代碼對我來說太複雜了。我的意思是我會允許用戶輸入他們的文件,如:new_file = raw_input(「輸入你的文件:」),輸出將在example.txt中 –

+0

你的意思是用戶輸入文件名?所以如果我輸入'example.txt',輸出會被寫入一個名字的文件中? –

+0

是的,用戶將輸入自己的文件,如a.txt或a.py ...並且該函數將打印一個新的特定文件,我將其命名爲example.txt.Overall,有一個來自用戶的文件,並且有一個在同一個地方創建新文件。 –