Reputation: 67
I have a python program that reads a csv file, makes some changes, then writes to an HTML file. The issue is a block of code where I'm trying to search for a string assigned to one variable, then replace it with another string assigned to another variable. I am able to read a line in the csv file that looks like this:
Link:,www.google.com
And I am successful in writing an html file with the following:
<tr><td>Link:</td><td><a href="https://www.google.com">www.google.com</a></td></tr>
Essentially I want to go further with an added step to find www.google.com between the anchor tags and replace it with "GOOGLE".
I've researched 'find and replace' functions built into python, and I came up with the substitution function inside the regular expressions module (re.sub()). This might not be the best way to do it and I'm trying to figure out if there's a better function/module out there I should look into.
python
for line in file:
newHTML.write(re.sub(var1,var2,line,flags=re.MULTILINE), end='')
newHTML.write(re.sub(var3,var4,line,flags=re.MULTILINE), end='')
The error I am receiving is:
newHTML.write(re.sub(var1,var2,line,flags=re.MULTILINE), end='')
TypeError: write() takes no keyword arguments
If I comment out this code, the rest of the program runs fine albeit without finding and replacing these variables.
Perhaps re.sub() doesn't go well with write()?
Upvotes: 1
Views: 82
Reputation: 642
The error says what the problem is: as @furas commented, write()
is not the same as print()
, and doesn't accept the end=''
keyword argument. file.write()
by default doesn't include newlines if you don't explicitly put any \n
's, so it should work if you change the line to:
newHTML.write(re.sub(var1,var2,line,flags=re.MULTILINE))
Also, regex and HTML aren't the best of friends... Your case is simple enough that using regex is fine, but you mentioned looking for a better module to generate HTML. This SO question had some good suggestions in the answers. Notable mentions for creating HTML templates on there were xml.etree, jinja2 (Flask's default engine), and yattag.
Upvotes: 1