Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Editing .html files using Python?

Tags:

python

I want to delete everything from my html file and add <!DOCTYPE html><html><body>.

Here is my code so far:

with open('table.html', 'w'): pass
table_file = open('table.html', 'w')
table_file.write('<!DOCTYPE html><html><body>')

After i run my code, table.html is now empty. Why?

How can I fix that?

like image 232
Michael Avatar asked Dec 09 '22 12:12

Michael


1 Answers

It looks like you're not closing the file and the first line is doing nothing, so you could do 2 things.

Either skip the first line and close the file in the end:

table_file = open('table.html', 'w')
table_file.write('<!DOCTYPE html><html><body>')
table_file.close()

or if you want to use the with statement do it like this:

with open('table.html', 'w') as table_file:
  table_file.write('<!DOCTYPE html><html><body>')
  # Write anything else you need here...
like image 110
Lipis Avatar answered Dec 11 '22 01:12

Lipis