Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
2  
You are missing the point of the with block... –  Matteo Italia Sep 30 '13 at 11:09
 
with open('table.html', 'w'): pass ; deletes everything from my file –  Michael Vayvala Sep 30 '13 at 11:13
add comment

3 Answers

up vote 7 down vote accepted

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...
share|improve this answer
4  
You don't need table_file.close() with the with statement –  mavroprovato Sep 30 '13 at 11:08
 
Thanks re provato.. ;) –  Lipis Sep 30 '13 at 12:28
add comment
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.

share|improve this answer
add comment

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.

share|improve this answer
 
with open('table.html', 'w'): pass ; deletes everything from my file –  Michael Vayvala Sep 30 '13 at 11:00
 
But why? You're doing the same one line after that. –  Matthias Sep 30 '13 at 11:19
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.