你不能寫一個關閉的文件。就在你的代碼的末尾移動out_file.close():
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()
這裏清潔的版本:
# 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'語句](https://www.python.org/dev/peps/pep-0343/)。它使得不可能無意中忽略「關閉」調用(不需要「關閉」調用),並且更容易查看資源何時可以使用。 – ShadowRanger