2015-10-25 46 views
-6

如果我在一行中包含例如「foo bar」的文件,如何將該文件轉換爲列表以便我可以打開foo文件和條形文件它?將列表中的值轉換爲Python中的文件名

編輯: 如果我有一個名爲'filenames'的文件包含'foo bar'內容,我將如何從創建列表開始打開foo文件,編輯其內容並將它們寫入到條形文件?這是我到目前爲止所做的。

import re 

def main(): 
    file = open('filenames.txt', 'r') 
    text = file.read().lower() 
    file.close() 
    text = re.sub('[^a-z\ \']+', " ", text) 
    words = list(text.split()) 

main() 
+0

你有沒有嘗試過任何代碼呢? – idjaw

+1

有很多方法可以做到這一點。發佈一些你嘗試過的代碼不能與錯誤消息一起工作,並詢問如何讓它工作 – josiah

+1

打開foo文件和條形文件是什麼意思?你的意思是'foo'是一個文件夾,'bar'是其中的一個文件?你到目前爲止嘗試過什麼嗎? –

回答

0

這裏有一個方法來做到這一點...

lst = list() 
with open(myfile) as f: 
    for line in f: 
     lst.extend(line.split(" ")) # assuming words in line are split by single space 
print lst # or whatever you want to do with this list 
0

打開文件名爲"filenames",讀的第一行,並獲得source文件的名稱來讀取和target文件寫:

現在,用以下代碼可以讀取源文件,做東西並將其寫入目標文件:

with open(source, 'r') as s: 
     # Read contents on file: 
     source_text = s.read() 

     # Do stuff with source text here 

     # Now, let's write it to the target file: 
     with open(target, 'w') as t: 
      t.write('stuff to write goes here') 

而就是這樣。

有關讀取和寫入文件的更多信息,請閱讀docs

+0

非常感謝,讓它工作沒有問題。我希望能夠在顯示新數據寫入之後打開目標文件,但似乎無法使其工作。任何線索,我該怎麼做呢?我試過更新=打開(目標,「R」),打印(更新),但它不會工作。 – JoC5

+0

要讀取文件的內容,打開它後必須使用函數'read()'。更多信息可在[docs](https://docs.python.org/2/tutorial/inputoutput.html)中找到。 –

相關問題