首页 > 解决方案 > Python OS For Loop - TypeError:“模块”对象不可调用

问题描述

我有以下代码来遍历文件夹中的每个文件并在其pdfplumber上运行模块:

#Import required packages:
import os
import pdfplumber

#Iterate over pdf's 
os.chdir(r'C:\MyDocuments\PDF')
directory = r'C:\MyDocuments\PDF'
for filename in os.listdir(directory):                              #iterate over each file in directory
    if filename.endswith(".pdf"):                                   #if the file is a pdf (we will be creating .txt files - do not want to include these)
        pdf = pdfplumber(filename)                                  #pdfplumber extracts the pdf file first
    else:
        continue

使用 导入 PDF 后,还有更多事情要做pdfplumber,但这个for循环给出了问题的要点。当我运行它时,我收到错误消息

TypeError: 'module' object is not callable

似乎应该有一个解决方案,例如:from os import ...where ... 应该是所需的任何功能(我认为)。如果这是一个解决方案,我不知道我需要从 os. 如果有人对如何使这项工作提出建议,我将不胜感激!

标签: pythonfor-looppdfmodule

解决方案


pdfplumber本身就是类名。您需要为此使用.open()

import os
import pdfplumber

#Iterate over pdf's 
os.chdir(r'C:\MyDocuments\PDF')
directory = r'C:\MyDocuments\PDF'
for filename in os.listdir(directory):                              #iterate over each file in directory
    if filename.endswith(".pdf"):                                   #if the file is a pdf (we will be creating .txt files - do not want to include these)
        pdf = pdfplumber.open(filename)                                  #pdfplumber extracts the pdf file first
    else:
        continue

推荐阅读