当前位置: 首页 > 知识库问答 >
问题:

保存文件在Python从输出

太叔昆
2023-03-14

这里有个问题。我有这个Python脚本,它检查大型数据集的电子邮件并提取它们。在我的mac上,它只显示终端中的所有电子邮件地址。有时文件是1-2演出,所以它可能需要一点,输出是疯狂的。我想知道在Python中,把它保存到一个文件中而不是在终端中打印出来有多容易。

我甚至不需要看到所有的东西都被扔进候机楼。

这是我正在使用的脚本

#!/usr/bin/env python
#
# Extracts email addresses from one or more plain text files.
#
# Notes:
# - Does not save to file (pipe the output to a file if you want it saved).
# - Does not check for duplicates (which can easily be done in the terminal).
#


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

共有3个答案

袁骏祥
2023-03-14

打印时,替换为write语句

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

在这种情况下,只需替换为

    for arg in args:
    if os.path.isfile(arg):
        for email in get_emails(file_to_str(arg)):
            with open (tempfile , 'a+') as writefile:
                writefile.write(name+'\n')

Temfile是输出文件的位置

何章横
2023-03-14

首先,您需要打开一个文件file=open('output','w')

然后,不要打印电子邮件,而是将其写入文件:file.write(email'\n')

正如jasonharper所说,您也可以在执行时将程序的输出重定向到一个文件。

钱渊
2023-03-14

与其打印,不如直接写入文件。

打开('filename.txt','w')作为f:f.write('{}\n'.format(email))

 类似资料:
  • 问题内容: 如何将URL输出的JSON保存到文件中? 例如,来自Twitter搜索API(此http://search.twitter.com/search.json?q=hi) 语言并不重要。 编辑//然后如何将进一步的更新附加到EOF? 编辑2 //确实,答案很好,但是我接受了我认为最优雅的答案。 问题答案: 这在任何语言中都很容易,但是机制各不相同。使用wget和shell: 追加: 使用P

  • 问题内容: 我是Python的新手。我需要从字典中查询项目并将结果保存到文本文件中。这是我所拥有的: 如何将打印的输出保存到文本文件? 问题答案: 让我总结所有答案并添加更多答案。 要从脚本中写入文件,需要使用Python提供的用户文件I / O工具(这是东西。 如果不想修改程序,则可以使用流重定向(在Windows和类似Unix的系统上)。这是东西。 如果您想 同时 在屏幕和日志文件中看到输出,

  • 问题内容: 我想通过Python将Shell命令的输出保存到文本文件中。这是我实际的,非常基本的python代码: 编辑 这里是最终脚本,谢谢您的帮助:) 问题答案: 尝试这样的事情: 编辑 :满足您的需求

  • 问题内容: 我在从文件读取,处理其字符串并将其保存到UTF-8文件时遇到问题。 这是代码: 然后,我对可变文本进行一些处理。 接着 这样可以完美地输出文件,但是根据我的编辑器,它在iso 8859-15中可以输出。由于相同的编辑器将输入文件(在变量文件名中)识别为UTF-8,所以我不知道为什么会这样。据我的研究表明,注释行应该可以解决问题。但是,当我使用这些行时,产生的文件主要具有特殊字符的乱码,

  • 问题内容: 我在所有技术术语上都不是很好,所以我会尽力解释我的问题。 我已经编写了一个小脚本来打开android SDK并检查连接的设备(使用Windows 10和python 2.7.14)。我得到的代码如下: 一切正常,但我想将最后3行保存到文本文件中。我尝试过使用并将其全部转换为字符串并将其写入文件并关闭它,但是它不起作用。它甚至都没有创建文件,更不用说向它写入任何内容了。 我可能缺少一些关