2013-08-19 35 views
1

我需要編寫一個Python腳本來讀取平面文本文件,搜索字符串並重寫爲新的文本文件。在Python中閱讀和搜索文本文件?

我有這樣的(例子)腳本:

import re 
read = open("file.txt", "r") 
data = file.read() 
print data 
newfile = open("newfile.txt", "w") 
for line in read: 
    if re.match("(.*)dst="+str_var"(.*)", line): 
    print newfile, line, 
file.close() 

是否有更簡單或更正確的方法是什麼? (我對Python幾乎一無所知,這段代碼來源於我在教程,谷歌等中找到的內容)

謝謝!

+4

是否行得通?如果不是,它究竟做了什麼? – Mat

+0

我還沒有運行它 - 這只是一個不完整的腳本的一部分。 – hjames

+0

你想完成什麼? – Augusto

回答

2

這可能做的伎倆

read_file = open("file.txt", "r") 
data = read_file.read() 
read_file.close() 
file_content = re.sub("\d+", "", data) 
word = your_word 
if word in file_content: 
    newfile = open("newfile.txt", "w") 
    print >> newfile, word 
    newfile.close()