2013-08-26 43 views
1

我需要能夠打開一個txt文件,將它作爲字符串讀取,使用正則表達式替換字符串中的項目(刪除非alpha和數字字符),然後寫入文件,以便原始文件被「清理」。使用正則表達式來修改Python中的多個文件

這看起來很簡單,但我是初學者,事實並非如此。我可以打開文件,在中間執行所有的操作,然後將更改保存到單個文件(使用glob和re.sub),但無法弄清楚如何對原始文件進行更改並保存。

所有幫助表示感謝!第一次海報謝謝。

回答

0

由於您似乎知道如何操作內容,我只是給你一個處理文件的框架。

try: 
    # 'r+' opens the file for both reading and writing 
    with open("gg.txt", "r+") as f: 
     # fetching the content 
     content = f.read() 
     # do your stuff here 

     # writing back the content 
     f.seek(0,0) 
     f.write(content) 
     f.truncate() 
except EnvironmentError: 
    print "oO" 
    #better error handling here 
    raise 

參見:http://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files

而對於截斷([大小):http://docs.python.org/2/library/stdtypes.html?highlight=truncate#file.truncate

+0

感謝。我會給它一個去讓你知道發生了什麼! – user2716595