4

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?

2
  • 3
    You are missing the point of the with block... Commented Sep 30, 2013 at 11:09
  • with open('table.html', 'w'): pass ; deletes everything from my file Commented Sep 30, 2013 at 11:13

3 Answers 3

9

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...
Sign up to request clarification or add additional context in comments.

2 Comments

You don't need table_file.close() with the with statement
Thanks re provato.. ;)
4
with open('table.html', 'w'): pass 
   table_file = open('table.html', 'w')
   table_file.write('<!DOCTYPE html><html><body>')

This would open the file table.html two time's and your not closing your file properly too.

If your using with then :

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

with closes the file automatically after the scope.

Else you have to manually close the file like this:

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

and you don't have to use the with operator.

Comments

1

I'm not sure what you're trying to achieve with the with open('table.html', 'w'): pass. Try the following.

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

You're currently not closing the file, so the changes aren't being written to disk.

2 Comments

with open('table.html', 'w'): pass ; deletes everything from my file
But why? You're doing the same one line after that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.