首页 > 解决方案 > 仅打开和读取目​​录内的目录文件

问题描述

这是我的新代码。由于某种原因,它给出了下面提供的错误。有人知道为什么会这样吗?或者我可以用什么方法来解决这个问题?

新代码:

import glob
import re

folder_path = "/home/"
file_pattern = "/**/*"
folder_contents = glob.glob(folder_path + file_pattern, recursive=True)

#Search for Emails
regex1= re.compile(r'\S+@\S+')
#Search for Phone Numbers
regex2 = re.compile(r'\d\d\d[-]\d\d\d[-]\d\d\d\d')

match_list=[]

for file in folder_contents:
    read_file = open(file, 'rt').read()
    if regex1.findall(read_file) or regex2.findall(read_file):

        email = regex1.findall(read_file)
        phone=regex2.findall(read_file)

        match_list.append(file)
        print (file)
        print (email)

以下是我收到的错误:

/home//sample.txt
['bcbs@aol.com', 'James@aol.com']
---------------------------------------------------------------------------
UnicodeDecodeError                        Traceback (most recent call last)
<ipython-input-44-6281ab1fc0ff> in <module>()
     15 
     16 for file in folder_contents:
---> 17     read_file = open(file, 'rt').read()
     18     if regex1.findall(read_file) or regex2.findall(read_file):
     19 

/jupyterhub_env/lib/python3.5/codecs.py in decode(self, input, final)
    319         # decode input (taking the buffer into account)
    320         data = self.buffer + input
--> 321         (result, consumed) = self._buffer_decode(data, self.errors, final)
    322         # keep undecoded input until the next call
    323         self.buffer = data[consumed:]

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc7 in position 10: invalid continuation byte

是否需要添加 if else 语句来指定文件类型或..................... ..................................................... ..................................................... ..................................................... ..................................................... ...

标签: pythonregexpython-3.xglobos.path

解决方案


glob模块通过指定recursive=True

folder_path = "/home/e136320"
file_pattern = "/**/*"
folder_contents = glob.glob(folder_path + file_pattern, recursive=True)

推荐阅读