Editing .html files using Python?

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

Here is my code:

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

After running my code is table.htmlnow empty. Why?

How can i fix this?

+4
source share
3 answers

It looks like you are not closing the file, and the first line does nothing, so you can do 2 things.

Or skip the first line and close the file at 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 operator with, follow these steps:

with open('table.html', 'w') as table_file:
  table_file.write('<!DOCTYPE html><html><body>')
  # Write anything else you need here...
+7
source
with open('table.html', 'w'): pass 
   table_file = open('table.html', 'w')
   table_file.write('<!DOCTYPE html><html><body>')

This will open the table.html file two times, and your file will also not be closed.

If you use with , then:

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

c automatically closes the file after the area.

:

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

.

+4

, with open('table.html', 'w'): pass. .

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

You are not currently closing the file, so changes are not written to disk.

+1
source

All Articles