如何让程序访问任何类型的文件?

时间:2017-04-12 10:07:37

标签: python python-3.x

我正在尝试创建一个通用的电子邮件提取器。我已经完成了如下程序:

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

我运行了这个程序,它在.txt.csv扩展名文件中运行良好。

但问题是我为此程序提供输入的文件夹还包含.xsls.doc.docx.mdb.pdf和其他扩展文件,其中也有电子邮件。我不明白如何修改我的程序来访问这些或任何类型的扩展文件并从中提取电子邮件。

请告诉我如何解决我的问题。

1 个答案:

答案 0 :(得分:0)

你应该打开文件' rb'标志

with open(filename, 'rb') as f:

请注意,doc,pdf,...不是文本文件,因此对于每种类型,您需要使用特殊解析器来解析内容