Catch links from a txt file
<p>I have a file txt, where there are severals lines... Some of these are links. My question is: How can I catch all this links and save them on another txt file? I'm a newbie.</p>

<p>I tried with this but it doesn't work:</p>

<pre><code>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)
</code></pre>

<p>You can't write to a closed file. Just move the out_file.close() at the end of your code:</p>

<pre><code>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()
</code></pre>

<p>Here a cleaner version:</p>

<pre><code># 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)
</code></pre>

<p>You can also combine the two with:</p>

<pre><code># 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)
</code></pre>

python python-3.x