如何将python输出保存到文本文件

时间:2016-11-07 09:30:42

标签: python

我尝试了很多方法将输出保存到文本文件,但它对我不起作用

这是代码

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

运行脚本时

它会在dos屏幕上打印电子邮件

我想将其保存到文本文件

3 个答案:

答案 0 :(得分:0)

您可以使用自己的代码替换以下代码。

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

答案 1 :(得分:0)

您的代码已经有一些打印语句(您应该使用记录器)但不是添加到代码来写入文件,为什么不只是

$ python myscript.py >> output.txt

这将在不添加代码的情况下为您提供完全相同的输出。

答案 2 :(得分:0)

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

OR

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

这会将print语句给出的输出提供给file_name.txt文件。