gpt4 book ai didi

python - 从 txt 文件中捕获链接

转载 作者:太空宇宙 更新时间:2023-11-04 10:08:11 26 4
gpt4 key购买 nike

我有一个 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.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)

关于python - 从 txt 文件中捕获链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39802143/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com