Krisem
Krisem

Reputation: 13

Printing output to file with Python

I am trying to create a script that takes a file as input, looks up all the email addresses, and writes them to a designated file.

based on other similar questions, i have ended up with this:

import re

    Input = open("inputdata.txt", "r")
    regex = re.compile("\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b")
    Logfile = "Result.txt"


        for line in Input:
            query = regex.findall(line)
            for line in query:
                print >>Logfile, query

what am i doing wrong? this outputs nothing. i am guessing the main problem is "for line in query:", which i have tried changing without any luck.

Cheers!

Edit: i have changed the script as suggested below, with "print (query)" instead. i still do not get any output. current script is:

import re

Input = open("Inputdata.txt", "r")
regex = re.compile("\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b")
# logfile = "Result.txt"

for line in Input:
    query = regex.findall(line)
    for line in query:
        with open("Result.txt", "a") as logfile:
            logfile.write(line)

It outputs nothing, and tells me: " NameError: name "logfile" not defined". what causes this, and is this the reason there is no output?

Upvotes: 0

Views: 126

Answers (2)

tobias_k
tobias_k

Reputation: 82949

Your Logfile variable is just the name of a file, not an actual file object. Also, you should use with to automatically close the file when you are done. Try this:

with open("Result.txt", "a") as logfile:
    print >>logfile, "hello world"
    print >>logfile, "another line"

But note that in Python 3.x, the syntax is different, as print is no longer a statement but a function:

with open("Result.txt", "a") as logfile:
    print("hello world", file=logfile)
    print("another line", file=logfile)

Thus, instead of redirecting print, the best choice might be to write to the file directly:

with open("Result.txt", "a") as logfile:
    logfile.write("hello world\n")
    logfile.write("another line\n")

Upvotes: 1

RatDon
RatDon

Reputation: 3543

I don't think, with print you can write to a file without redirecting the output to a file. The way you have used the print, I guess, you want output redirection only.

Let's say your python script is in a file test.py. replace the line:

print >>Logfile, query

with just:

print query

And from a terminal/cmd, run the script like this:

python test.py >> Result.txt

This is called output redirection.

Upvotes: 0

Related Questions