2016-10-01 4 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

В чем это не работает? Вы закрываете файл, который вы пытаетесь написать, _before_, вы пишете на него. Похоже, это может быть проблемой. –

+2

Боковое примечание: используйте ['with' statements] (https://www.python.org/dev/peps/pep-0343/) при работе с файлами. Это делает невозможным случайное опускание вызова 'close' (вызов' close' не требуется) и упрощает просмотр, когда ресурс может быть использован. – 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) 
Смежные вопросы