python - 仅打开和读取目录内的目录文件
问题描述
这是我的新代码。由于某种原因,它给出了下面提供的错误。有人知道为什么会这样吗?或者我可以用什么方法来解决这个问题?
新代码:
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 语句来指定文件类型或..................... ..................................................... ..................................................... ..................................................... ..................................................... ...
解决方案
该glob
模块通过指定recursive=True
:
folder_path = "/home/e136320"
file_pattern = "/**/*"
folder_contents = glob.glob(folder_path + file_pattern, recursive=True)
推荐阅读
- javascript - 如何更改在 TinyMCE 中插入图像的功能?
- python - 未查询完整块时,Modbus RTU 出现异常 2(非法数据地址)
- java - 使用 Junit 测试从 Java AWS S3 客户端禁用调试日志记录
- python - 从列表中将键值附加到字典
- java - UnfinishedStubbingException mokito
- python - snakemake - 检查点和通配符
- python-3.x - 如何跳过文件中的文本行并在最后读取 numbes 列 - Python 3
- c++ - 使用 (pointedToType*) 指针显示字符指针
- azure - 如何在 CI 管道中使用 Az CLI?
- ios - Xcode 11.3.1 的场景工具包编辑器“速度场”(SKVelocityFieldNode)有什么作用?