2016-10-01 100 views
1

我有一个文件txt,其中有几行...其中有些是链接。我的问题是:如何捕获所有这些链接并将它们保存在另一个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) 
+2

在哪方式不起作用?您正在关闭正在尝试写入的文件,在写入该文件之前。似乎这可能是一个问题。 –

+2

附注:处理文件时,请使用['with'语句](https://www.python.org/dev/peps/pep-0343/)。它使得不可能无意中忽略“关闭”调用(不需要“关闭”调用),并且更容易查看资源何时可以使用。 – ShadowRanger

回答

4

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