2013-09-30 2 views
4

내 html 파일에서 모든 것을 삭제하고 <!DOCTYPE html><html><body>을 추가하고 싶습니다. 난 내 코드를 실행 한 후Python을 사용하여 .html 파일을 편집 하시겠습니까?

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

, table.html 지금 비어 :

여기에 지금까지 내 코드입니다. 왜?

어떻게 해결할 수 있습니까?

+3

'with'블록의 요점을 놓치고 있습니다 ... –

+0

open ('table.html', 'w') : pass; 내 파일에서 모든 것을 지운다 –

답변

7

파일을 닫지 않은 것처럼 보입니다. 첫 번째 줄은 아무 것도하지 않으므로 2 가지 작업을 수행 할 수 있습니다. 당신이 with 문을 사용하려는 경우 또는 다음과 같이 그것을 할

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

:

하나는 첫 번째 줄을 건너 뛰고 결국 파일을 닫습니다

with open('table.html', 'w') as table_file: 
    table_file.write('<!DOCTYPE html><html><body>') 
    # Write anything else you need here... 
+4

'with' 문과 함께'table_file.close()'이 필요 없다. – mavroprovato

+0

감사합니다.;) – Lipis

1

잘 모르겠어요 with open('table.html', 'w'): pass으로 달성하려는 목표. 다음을 시도하십시오.

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

현재 파일을 닫지 않아 변경 사항이 디스크에 기록되지 않습니다.

+0

with open ('table.html', 'w') : pass; 내 파일에서 모든 것을 지운다 –

+0

하지만 왜? 그 후 같은 줄을하고 있습니다. – Matthias

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

이렇게하면 table.html 파일이 두 번 열리고 파일을 제대로 닫지 않습니다.

당신의 다음와 를 사용하는 경우 :

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

자동 범위 후 파일을 닫습니다.

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

당신은 운영자로를 사용할 필요가 없습니다 : 그렇지

수동이 같은 파일을 닫해야합니다.

관련 문제