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

# 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) 

をあなたはまた、2つを組み合わせることができますそれはうまくいかないのですか?書き込みしようとしているファイルを閉じる前に、そのファイルに書き込みます。それが問題になるかもしれないようです。 –

+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/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) 
関連する問題