你不能写一个关闭的文件。就在你的代码的末尾移动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