读取目录中的所有文件,并输出包含某些正则表达式的文件

问题描述 投票:2回答:3

我试图读取我的目录中的所有文件并输出包含正则表达式的文件以及每个文件中的正则表达式。

 import glob
import re
import PyPDF2
#-------------------------------------------------Input----------------------------------------------------------------------------------------------
folder_path = "/home/"
file_pattern = "/*"
folder_contents = glob.glob(folder_path + file_pattern)

#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:

    if re.search(r".*(?=pdf$)",file):
        #this is pdf
        with open(file, 'rb') as pdfFileObj:
            pdfReader = PyPDF2.PdfFileReader(pdfFileObj) 
            pageObj = pdfReader.getPage(0)  
            content = pageObj.extractText()
            read_file = open(file,'rb')
            #print("{}".format(file))

    elif re.search(r".*(?=csv$)",file):
        #this is csv
        with open(file,"r+",encoding="utf-8") as csv:
            read_file = csv.read()
            #print("{}".format(file))
    elif re.search(r"/jupyter",file):
        print("wow")
    elif re.search(r"/scikit",file):
        print("wow")
    else:
        read_file = open(file, 'rb').read()
       #print("{}".format(file))
        continue
    if regex1.findall(read_file) or regex2.findall(read_file):
                print(read_file)

我设法写下面的代码,但它给出以下错误:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-39-f614d35e0441> in <module>()
     38        #print("{}".format(file))
     39         continue
---> 40     if regex1.findall(read_file) or regex2.findall(read_file):
     41                 print(read_file)

TypeError: expected string or bytes-like object

有没有办法让这个没有错误工作?

python regex glob pypdf2 os.path
3个回答
0
投票

用以下内容替换您的读取文件代码:

with open(File, mode='rb') as file:
    readFile = file.read()

0
投票

read()只有open(filename)将工作。只需替换为此,您就可以解决问题。

read_file = open(file).read()

0
投票

首先,我向回答这个问题的其他人道歉,因为我会说一些关于OP前问题的事情。

关于OP,你不应该不假思索地复制代码。

Content是您已阅读的页面。这意味着你的代码应该是read_file = content。为什么我写read_file = #,因为我认为你会添加额外的代码。但它不应该再次读取相同的文件。

with open(file, 'rb') as pdfFileObj:
        pdfReader = PyPDF2.PdfFileReader(pdfFileObj) 
        pageObj = pdfReader.getPage(0)  
        content = pageObj.extractText()
        read_file = open(file,'rb') 
        #^---^---^ according to your former question, `read_file` should  be `content`

并且会出现其他问题。你应该在continue之后添加print("wow")

elif re.search(r"/jupyter",file):
    print("wow")
elif re.search(r"/scikit",file):
    print("wow")

否则,当发生错误时,您的代码将继续运行。因为你没有读过任何东西。

if regex1.findall(read_file) or regex2.findall(read_file):
    print(read_file)
© www.soinside.com 2019 - 2024. All rights reserved.