4

HTMLファイルからすべてを削除して追加したい<!DOCTYPE html><html><body>.

これまでの私のコードは次のとおりです。

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

コードを実行した後、table.html空になりました。なんで?

どうすれば修正できますか?

4

3 に答える 3

9

ファイルを閉じていないようで、最初の行は何もしていないため、2 つのことを行うことができます。

最初の行をスキップして、最後にファイルを閉じます。

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 が 2 回開かれ、ファイルも適切に閉じられません。

次に使用する場合:

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 に答える