2014-04-04 27 views
4

我正在嘗試使用python爲列表中的每個項目創建單獨的文本文件。Python - 爲列表中的每個項目創建文件

List = open('/home/user/Documents/TestList.txt').readlines() 
List2 = [s + ' time' for s in List] 
for item in List2 open('/home/user/Documents/%s.txt', 'w') % (item) 

該代碼應該從目標文本文件生成一個列表。第二個列表是使用第一個列表中的字符串和一些附錄生成的(在這種情況下,在末尾添加「時間」)。我的第三條線是我遇到問題的地方。我想爲我的新列表中的每個項目創建一個單獨的文本文件,其中文本文件的名稱是該列表項的字符串。例如:如果我的第一個列表項是'健康時間',第二個列表項是'食物時間',則會生成稱爲「健康時間.txt」和「食物時間.txt」的文本文件。

看來我遇到了打開命令的問題,但我已經廣泛搜索,沒有發現任何關於在列表上下文中使用open的問題。

+0

你跑哪個問題?錯誤信息? – Beryllium

回答

5

首次使用發電機

List = open("/path/to/file") #no need to call readlines (a filehandle is naturally a generator of lines) 
List2 = (s.strip() + ' time' for s in List) #calling strip will remove any extra whitespace(like newlines) 

這會導致懶惰的評價,所以你不循環和循環和循環等

然後修復您的線路(這是導致在你的程序中錯誤的實際問題

for item in List2: 
    open('/home/user/Documents/%s.txt'%(item,), 'w') 
      # ^this was your actual problem, the rest is just code improvements 

使你的整個代碼變得

List = open("/path/to/file") #no need to call readlines (a filehandle is naturally a generator of lines) 
List2 = (s.strip() + ' time' for s in List) 
for item in List2: #this is the only time you are actually looping through the list 
    open('/home/user/Documents/%s.txt'%(item,), 'w') 

現在你只通過列表循環的3倍

建議一個時間,而不是使用文件路徑變量,以形成你的文件名也是一個非常不錯的一個

3

移動你的標記化的文件路徑字符串。現在它不在電話open之內。

for item in List2: 
    filePath = '/home/user/Documents/%s.txt' % (item) 
    open(filePath, 'w') 
相關問題