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?

4

3 回答 3

9

看起来你没有关闭文件,第一行什么也没做,所以你可以做两件事。

跳过第一行并最后关闭文件:

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

或者,如果您想使用该with语句,请执行以下操作:

with open('table.html', 'w') as table_file:
  table_file.write('<!DOCTYPE html><html><body>')
  # Write anything else you need here...
于 2013-09-30T10:59:07.957 回答
4
with open('table.html', 'w'): pass 
   table_file = open('table.html', 'w')
   table_file.write('<!DOCTYPE html><html><body>')

这将打开文件 table.html 两次,并且您也没有正确关闭文件。

如果您then 一起使用:

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

with在作用域之后自动关闭文件。

否则,您必须像这样手动关闭文件:

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

而且您不必使用with运算符。

于 2013-09-30T11:04:48.913 回答
1

我不确定你想用with open('table.html', 'w'): pass. 试试下面的。

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

您当前没有关闭文件,因此不会将更改写入磁盘。

于 2013-09-30T10:59:14.010 回答