Answer to Question #39053 in Python for Sai

Question #39053
I am having two types of files. type1 : 2009.htm, 2010.htm, 2011.htm, 2012.htm type2: file1.txt, file2.txt, file3.txt, file4.txt now I have to process the .htm file and write the processed data into the .txt file. the code for the processing is : f = open('2009.htm', 'r+') text = f.read() pattern = "" for match in re.findall(pattern, text): if True: html = text.replace("", " ") f1 = open('file1.txt', 'r+') f1.write(html) f1.close() now I have to automate this for all the files using for loops. i have tried one code but in that only the first file is getting copied into all the files. list1 = ['2009.htm', '2010.htm', '2011.htm', '2012.htm', '2013.htm'] list2 = ['file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', 'file5.txt'] for x in list1: for y in list2: f = open(x, 'r+') text = f.read() pattern = "" for match in re.findall(pattern, text): if True: html = text.replace("", " ") f1 = open(y, 'r+') f1.write(html) f1.close() now what I have do?
1
Expert's answer
2014-03-05T12:38:26-0500
We propose the following way:


import re;


list1 = ['D:\2009.htm', 'D:\2010.htm']
list2 = ['D:\file1.txt', 'D:\file2.txt']
for x in zip(list1, list2):
f = open(x[0], 'r+')
text = f.read()
pattern = "aaa"
for match in re.findall(pattern, text):
if True:
html = text.replace("aaa", "bbb")
f1 = open(x[1], 'w+')
f1.write(html)
f1.close()
f.close();


Here zip function allows to obtain input file name as x[0] (because list1 is the first argument), and the output file name as x[1] (because list2 is the second argument in zip), see http://docs.python.org/2/library/functions.html#zip for details.

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be first!

Leave a comment

Ask Your question

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS
paypal