2016-10-01 30 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)