-2

I tried many way to save output to text file but it don't work for me

this is code

from optparse import OptionParser
import os.path
import re

regex = re.compile(("([a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`"
                    "{|}~-]+)*(@|\sat\s)(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(\.|"
                    "\sdot\s))+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)"))

def file_to_str(filename):
    """Returns the contents of filename as a string."""
    with open(filename) as f:
        return f.read().lower() # Case is lowered to prevent regex mismatches.

def get_emails(s):
    """Returns an iterator of matched emails found in string s."""
    # Removing lines that start with '//' because the regular expression
    # mistakenly matches patterns like 'http://foo@bar.com' as '//foo@bar.com'.
    return (email[0] for email in re.findall(regex, s) if not email[0].startswith('//'))

if __name__ == '__main__':
    parser = OptionParser(usage="Usage: python %prog [FILE]...")
    # No options added yet. Add them here if you ever need them.
    options, args = parser.parse_args()

    if not args:
        parser.print_usage()
        exit(1)



    for arg in args:
        if os.path.isfile(arg):
            for email in get_emails(file_to_str(arg)):

                print email

        else:
            print '"{}" is not a file.'.format(arg)
parser.print_usage()

when you run script

it will print emails in dos screen

I want save it to text file

YazOT
  • 13
  • 2
  • 5
  • 2
    Possible duplicate of [Correct way to write line to file in Python](http://stackoverflow.com/questions/6159900/correct-way-to-write-line-to-file-in-python) – JRodDynamite Nov 07 '16 at 09:32
  • 1
    Where in your code are you trying to write to a file? – cdarke Nov 07 '16 at 09:37
  • It looks like you want us to write some code for you. While many users are willing to produce code for a coder in distress, they usually only help when the poster has already tried to solve the problem on their own. A good way to show this effort is to include the code you've written so far, example input (if there is any), the expected output, and the output you actually get (console output, tracebacks, etc.). The more detail you provide, the more answers you are likely to receive. Check the [FAQ](http://stackoverflow.com/tour) and [How to Ask](http://stackoverflow.com/help/how-to-ask). – Rory Daulton Nov 07 '16 at 09:54
  • To clarify, please write some code that attempts to save to a text file. If you have no idea, read a python tutorial or the link given in the first comment. Come back to us after you have learned the basics and have tried something. – Rory Daulton Nov 07 '16 at 09:55

3 Answers3

0

You can replace the below code with your own.

 file = open(output_path, 'w')
 for arg in args:
    if os.path.isfile(arg):
        for email in get_emails(file_to_str(arg)):
            file.write(email + '\n')
    else:
            print '"{}" is not a file.'.format(arg)
 file.close()
amin
  • 1,413
  • 14
  • 24
0

Your code already has a few print statements (You should use a logger instead) but instead of adding to code to write to a file, why not just

$ python myscript.py >> output.txt

That will give you the exact same output without adding code.

Giannis Katsini
  • 1,209
  • 10
  • 13
0

$ python your_script.py > path/to/output_file/file_name.txt

OR

$ python your_script.py >> path/to/output_file/file_name.txt

This will give the output given by your print statements into file_name.txt file.

Vishvajit Pathak
  • 3,351
  • 1
  • 21
  • 16