的Python:遍历多个文本文件,提取目标串,并追加他们列出
问题描述:
(Python的3.6.3)的Python:遍历多个文本文件,提取目标串,并追加他们列出
我需要从包含长文本字符串多个文本文件中提取IP地址和日期。在此之后,我想将这些数据追加到Python列表中。这些文本文件也驻留在子目录中,所以我使用'os.path.join(subdir,file)来确保脚本捕获这些文件。
这里是我的代码:
ip_address = []
dates = []
for subdir, dirs, files in os.walk(rootdir):
for file in files:
if file.endswith('.txt'):
text_data = open(os.path.join(subdir, file))
ip_address.append(re.findall(r'[0-9]+(?:\.[0-9]+){3}', text_data))
dates.append(re.findall(r'[0-9]+(?:\/[0-9]+){2}', text_data))
else:
pass
不过,我得到以下错误:
TypeError Traceback (most recent call last)
<ipython-input-28-de806e6c6270> in <module>()
6 if file.endswith('.txt'):
7 text_data = open(os.path.join(subdir, file))
----> 8 ip_address.append(re.findall(r'[0-9]+(?:\.[0-9]+){3}', text_data))
9 dates.append(re.findall(r'[0-9]+(?:\/[0-9]+){2}', text_data))
10 else:
C:\Users\591159\AppData\Local\Continuum\Anaconda3\lib\re.py in findall(pattern, string, flags)
220
221 Empty matches are included in the result."""
--> 222 return _compile(pattern, flags).findall(string)
223
224 def finditer(pattern, string, flags=0):
TypeError: expected string or bytes-like object
我以为我试图提取数据是不以字符串形式,但不完全明白它的意思。我很欣赏任何指向正确方向的指针。谢谢!
答
从@AChampion采取的建议后,我修改了代码以下,它按预期工作:
ip_address = []
dates = []
for subdir, dirs, files in os.walk(rootdir):
for file in files:
if file.endswith('.txt'):
with open(os.path.join(subdir, file), 'r', encoding='utf8') as text_file:
text_data = text_file.read().replace('\n', '')
ip_address.append(re.findall(r'[0-9]+(?:\.[0-9]+){3}', text_data))
dates.append(re.findall(r'[0-9]+(?:\/[0-9]+){2}', text_data))
else:
pass
您的意思是在为'阅读()'数据 - 例如'text_data.read()'目前,'text_data'是字符串的迭代器,而不是字符串。 – AChampion
是的,我打算以字符串形式读取数据。我应该用什么方法来替换我的代码?提前致谢。 – comproch