Reputation: 449
I need to write a Python script that reads a flat text file, searches for a string, and rewrites into a new text file.
I have this (example) script:
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()
Is there an easier or more correct way? (I know pretty much nothing about Python. This code is derived from what I've found in tutorials, google, etc.)
Thanks!
Upvotes: 1
Views: 267
Reputation: 769
This may do the trick
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()
Upvotes: 2