2014-10-09 84 views
1

我有一個python列表['a','b','c'],它是在for循環中生成的。我想將列表中的每個元素寫入一個新文件。以編程方式將列表的內容寫入目錄

我曾嘗試:

counter = 0 
for i in python_list: 
    outfile = open('/outdirectory/%s.txt') % str(counter) 
    outfile.write(i) 
    outfile.close() 
    counter += 1 

我得到一個錯誤:

IOError: [Erno 2] No suchfile or directory. 

如何通過編程方式創建和寫入文件在for循環?

+0

是否目錄'/ outdirectory'存在? – moooeeeep 2014-10-09 17:21:26

回答

2

你沒有傳遞一個模式來打開,所以它試圖以讀取模式打開。

outfile = open('/outdirectory/%s.txt' % str(counter), "w") 

試試這個:

out_directory = "/outdirectory" 
if not os.path.exists(out_directory): 
    os.makedirs(out_directory) 

for counter in range(0, len(python_list)): 
    file_path = os.path.join(out_directory, "%s.txt" % counter) 
    with open(file_path, "w") as outfile: 
     outfile.write(python_list[counter]) 
+0

謝謝,我是python新手,忽略了開放模式。 – mech 2014-10-09 17:32:05

+0

NP,請查看其他答案,建議進一步改進,我已經發布了一個更完整的示例 – ErlVolton 2014-10-09 17:32:36

2

幾點建議:

  • 使用with語句用於處理文件 [docs]
  • 使用正確的文件打開模式編寫[docs]
  • 您只能在實際存在的目錄中創建文件。您的錯誤消息可能表示對open()的呼叫失敗,可能是因爲該目錄不存在。要麼你有錯別字,要麼你需要先創建目錄(例如,如this question)。

例子:

l = ['a', 'b', 'c'] 
for i, data in enumerate(l): 
    fname = 'outdirectory/%d.txt' % i 
    with open(fname, 'w') as f: 
     f.write(data) 
2

基本上你得到的消息是因爲你試圖打開一個名爲/outdirectory/%s.txt文件。 ErlVolton顯示的以下錯誤是您不以書寫模式打開文件。此外,您必須檢查您的目錄是否存在。如果您使用/outdirectory它意味着從文件系統的根目錄。

三pythonic額外: - 列舉自動計算列表中的項目的迭代器 - 與語句autoclose您的文件。 - 格式可以比%的事情

這樣的代碼可以在以下

for counter,i in enumerate(python_list): 
    with open('outdirectory/{}.txt'.format(counter),"w") as outfile: 
     outfile.write(i) 

PS寫更清楚一點:下一次顯示完整回溯

+0

謝謝,我從未見過枚舉。看起來像一個整潔的伎倆。 – mech 2014-10-09 17:36:06

相關問題