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
空になりました。なんで?
どうすれば修正できますか?
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
空になりました。なんで?
どうすれば修正できますか?
ファイルを閉じていないようで、最初の行は何もしていないため、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...
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演算子を使用する必要はありません。
で何を達成しようとしているのかわかりませんwith open('table.html', 'w'): pass
。以下を試してください。
with open('table.html', 'w') as table_file:
table_file.write('<!DOCTYPE html><html><body>')
現在ファイルを閉じていないため、変更はディスクに書き込まれません。