【问题标题】:Run a python script on all files in a directory对目录中的所有文件运行 python 脚本
【发布时间】:2021-02-19 17:48:04
【问题描述】:

第一次在这里发布问题,希望有经验/尝试过的人分享您的见解...在过去的几天和晚上,我一直在努力做到这一点...现在我无处可去在目录中的每个文件上循环此脚本。

基本上,这两个脚本工作得很好,它带来了一个 pdf 文件并将其更改为一个 excel 工作簿。现在我需要做的是浏览选定目录中的所有文件并执行相同的工作。


我一直卡在打开文件阶段 - 这是说不能调用数据(pdf 页面 - 数据 [0])吗?还是我应该添加更多阶段以将数据集引入...?

我是否必须为数据集创建一个列表,以便我可以调用数据,因为您需要调用的数据不止一个。这就是为什么 python 可以读取数据[0] ???

修改后的脚本

# import 
import os
import glob
import pdftotext
import openpyxl
from pathlib import Path
from string import ascii_uppercase

# open a pdf file
def to_excel(pdf_file):
    with open(pdf_file,'rb') as f: 
        data = pdftotext.PDF(f)
        
# operate data to get titles, values 
datas = data[0].split('\r\n')

finalData = list()
for item in datas:
    if item != '':
        finalData.append(item)

finalDataRefined = list()
for item in finalData:
    if item != '                          BCA Scheduled Maintenance Questions' and item != ' Do you suspect there is Asbestos at the property?' and item != '    Yes' and item != '    No' and item != '\x0c':
        finalDataRefined.append(item.strip())

titles = list()
values = list()

for num, item in enumerate(finalDataRefined):
    if num % 2 == 0:
        titles.append(item)
    else:
        values.append(item)

# get an output file name
       
OPRAST = values[1]
filename = work_dir / f"{OPRAST}.xlxs"

# create an excel workbook
excel_file = openpyxl.Workbook()
excel_sheet = excel_file.active

excel_sheet.append([])

alphaList = list(ascii_uppercase)
for alphabet in alphaList:
    excel_sheet.column_dimensions[alphabet].width = 20

excel_sheet.append(titles)
excel_sheet.append(values)

# save the excel workbook
excel_file.save(filename)
excel_file.close

# run a python script every file in a directory
alphaList = list(ascii_uppercase)

work_dir = Path(r"C:\Users\Sunny Kim\Downloads\Do Forms")
for pdf_file in work_dir.glob("*.pdf"):
    to_excel(pdf_file)

【问题讨论】:

  • 尝试将您的第二个脚本包装在一个函数中,并为 abspath 的每个元素调用它。它还有助于将所有导入语句保留在文件的顶部。
  • 感谢您的评论,我尝试使用函数(def)扭曲第二个脚本并尝试但仍然无法弄清楚如何循环目录中的所有文件....
  • 你确定你有data = pdftotext.PDF(f) 执行吗?试试print(type(data)),如果得到WindowsPath,那么data = pdftotext.PDF(f) 不会被执行。正如我之前提到的,现在你的data 对象是不是pdf 内容对象,而是**WindowsPath**对象(由报告的错误指示),这意味着它是一个路径(路径 I意味着像C:\Users\Sunny Kim\Downloads\Do Forms\a.pdf这样的str而不是文件centent(比如你的pdf页面内容title, value, balabala),只有在你打开这个路径并阅读文件后,你才能得到pdf页面内容并使用data[0]得到第一页.
  • 另外一件事,你的代码缩进还不清楚......,我猜你只是直接从 jupyter notebook 粘贴它们。在 python 中,如果你没有提供正确的缩进,除了猜测之外,你很难理解你的代码逻辑。例如,函数to_excel 中的语句datas = data[0].split('\r\n')?在您的代码中,它不是,但它应该是。你能看到我在回答中提供的代码吗?
  • 嘿赵,你现在是 100% 一切正常,它是缩进错误 - 我从下面的脚本中修复了它,现在它工作得很好!!!你是个传奇!非常感谢,我现在都不知道该说什么了:-)我很感激

标签: python for-loop absolute-path pdftotext


【解决方案1】:

我基本上知道你想做什么,但是你的代码的缩进不是那么可读……尤其是它是 python。

您的目标是为您的前缀目录中的每个 pdf 文件创建一个 excel?还是将所有 pdf 文件聚合到一个 excel 文件中?

下面的代码是针对第一个目标的。

代码逻辑。

  1. 获取所有pdf文件
  2. 循环遍历所有 pdf 文件,每个:
    1. 打开pdf文件
    2. 一些操作
    3. 导出为 excel 文件

你的完整代码可能是这样的(只是猜测):

# ----------------import part-------------------
import os
import glob
import pdftotext
import openpyxl
from string import ascii_uppercase
from pathlib import Path

def to_excel(pdf_file):
    with open(pdf_file, 'rb') as f: # this open the pdf file
        data = pdftotext.PDF(f)
    # ---------------operate the data, get title and value-----------
    datas = data[0].split('\r\n')

    finalData = list()
    for item in datas:
        if item != '':
            finalData.append(item)

    finalDataRefined = list()
    for item in finalData:
        if item != '                          BCA Scheduled Maintenance Questions' and item != ' Do you suspect there is Asbestos at the property?' and item != '    Yes' and item != '    No' and item != '\x0c':
            finalDataRefined.append(item.strip())

    titles = list()
    values = list()
    for num, item in enumerate(finalDataRefined):
        if num % 2 == 0:
            titles.append(item)
        else:
            values.append(item)

    # ------------------get output file name---------------------
    OPRAST = values[1]
    filename = work_dir / f"{OPRAST}.xlxs"
    # ------------------create excel file sheet------------------
    excel_file = openpyxl.Workbook()
    excel_sheet = excel_file.active

    excel_sheet.append([])

    alphaList = list(ascii_uppercase)
    for alphabet in alphaList:
        excel_sheet.column_dimensions[alphabet].width = 20

    excel_sheet.append(titles)
    excel_sheet.append(values)
    # --------------------save----------------
    excel_file.save(filename)
    excel_file.close
# -------------------main program---------------
alphaList = list(ascii_uppercase)
work_dir = Path(r"C:\Users\Sunny Kim\Downloads\Do Forms")

for pdf_file in work_dir.glob("*.pdf"):
    to_excel(pdf_file)

【讨论】:

  • 谢谢赵 - 我卡住的地方是打开 pdf 文件来运行脚本。如果你有时间看,我已经附上了整个脚本来告诉你我在哪里...
  • 而且我不明白 - export_xlsx_name 的作用 - 这应该转到脚本的最后一个以填充 excel 工作簿吗?
  • export_xlsx_name 只是代码中的filename,即excel文件的输出名称。错误是因为您将 pdf 文件路径视为 pdf 文件内容...我在修改后的答案中添加了完整代码。
  • 赵大喊你!我认为您将我带到了将脚本放在一起的这个阶段-非常感谢,是的,我的最终目标是将所有数据放入一个 excel 工作簿中-但是,现在我将其填充到单个 excel 工作簿中。所以你对我的理解是正确的......如果可以的话,请查看修改后的脚本 - 我仍然卡在这个阶段 - 调用数据来操作 - 希望代码现在看起来......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-07
  • 1970-01-01
相关资源
最近更新 更多