당신은 닫힌 파일에 쓸 수 없습니다. 여기
filee = open("myfile.txt").readlines()
out_file = open("out.txt","w")
out_file.write("")
for x in filee:
if x.startswith("http"):
out_file.write(x)
print (x)
out_file.close()
깨끗한 버전 : : 그냥 코드의 끝 부분에 out_file.close()를 이동
# open the input file (with auto close)
with open("myfile.txt") as input_file:
# open the output file (with auto close)
with open("out.txt", "w") as output_file:
# for each line of the file
for line in input_file:
# append the line to the output file if start with "http"
if line.startswith("http"):
output_file.write(line)
는 또한 결합 할 수 있습니다를 두 가지로 :
# open the input/output files (with auto close)
with open("myfile.txt") as input_file, open("out.txt", "w") as output_file:
# for each line of the file
for line in input_file:
# append the line to the output file if start with "http"
if line.startswith("http"):
output_file.write(line)
무엇을에서 방법은 작동하지 않습니까? 쓰기 전의 파일을 닫고 있습니다. 쓰기 전입니다. 그게 문제가 될 것 같아. –
사이드 노트 : 파일을 다룰 때는 ['with' statements] (https://www.python.org/dev/peps/pep-0343/)를 사용하십시오. 실수로 'close'호출을 생략 할 수 없으며 (close 호출이 필요하지 않음) 리소스를 사용할 수있는 시점을보다 쉽게 알 수 있습니다. – ShadowRanger