Python 从txt文件捕获链接
我有一个文件txt,其中有几行。。。其中一些是链接。我的问题是:如何捕获所有这些链接并将它们保存到另一个txt文件中?我是个新手 我试过这个,但不起作用:Python 从txt文件捕获链接,python,python-3.x,Python,Python 3.x,我有一个文件txt,其中有几行。。。其中一些是链接。我的问题是:如何捕获所有这些链接并将它们保存到另一个txt文件中?我是个新手 我试过这个,但不起作用: filee = open("myfile.txt").readlines() out_file = open("out.txt","w") out_file.write("") out_file.close() for x in filee: if x.startswith("http"): out_file.wri
filee = open("myfile.txt").readlines()
out_file = open("out.txt","w")
out_file.write("")
out_file.close()
for x in filee:
if x.startswith("http"):
out_file.write(x)
print (x)
无法写入已关闭的文件。只需将代码末尾的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)
无法写入已关闭的文件。只需将代码末尾的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)
旁注:处理文件时使用。这样就不可能意外忽略close
调用(不需要close
调用),并且更容易看到何时可以使用资源。旁注:在处理文件时使用。这样就不可能意外忽略close
调用(不需要close
调用),并且更容易看到何时可以使用资源。