从Python中的目录创建与其pdf文件名对应的多个文本文件

2024-09-25 08:36:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我只是开始尝试用文件转换来练习python。请帮我解决这个问题

我正在尝试将.PDF文件转换为.TXT文件,我可以使用以下代码将其转换为单个文件:

import pdfplumber

pdfPath = r'C:\Users\xyz\pdffiles\abc.pdf'

txtPath = r'C:\Users\xyz\txtfiles\abc.txt'

with pdfplumber.open(pdfPath) as pdf:
    for page in pdf.pages:
        text = page.extract_text()
        with open( txtPath, encoding='utf-8', mode='a') as f:
            f.write(text)    
print("Operation Success!") 

以上代码正在运行。 但是,我希望自动化我的“..\pdffiles”目录中所有多个pdf文件的处理过程,并在“..\txtfiles”目录中创建相应的文本文件,其名称与使用循环的pdf对应文件的名称相同。有人能帮我完成这项工作吗

任何建议都将不胜感激!! 你好


Tags: 文件代码textpdfaswithopenusers
2条回答

您可以使用os库中的listdir函数

https://docs.python.org/3/library/os.html#os.listdir

使用包含pdf文件(pdf文件)的文件夹的路径调用此函数。这将返回该文件夹中所有pdf文件的列表

循环浏览该列表,从文件中删除pdf扩展名,并将其用作txt文件名

例如

import os

folder_pdf = os.listdir('C:\Users\xyz\pdffiles')
for file in folder_pdf:
    name, ext = file.split('.')
    txt_path = f'C:\Users\xyz\txtfiles\{name}.txt'
    pdf_path = f'C:\Users\xyz\pdffiles\{file}'
    # Code to read pdf and write to text file
import os
import pdfplumber

path_to_your_files = "/path/to/your/pdffiles"
for filename in os.listdir(path_to_your_files):
    
    absolute_file_path = os.path.join(path_to_your_files, filename)
    with pdfplumber.open(absolute_file_path) as pdf:
        for page in pdf.pages:
            text = page.extract_text()
            with open(
                    os.path.splitext(absolute_file_path)[0] + ".txt", encoding="utf-8", mode="a"
            ) as f:
                f.write(text)
    print("Operation Success!")

相关问题 更多 >