脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|shell|

服务器之家 - 脚本之家 - Python - python读取多类型文件夹中的文档内容

python读取多类型文件夹中的文档内容

2024-04-01 10:06学地理的小胖砸 Python

无论我们使用哪种编程语言,处理文件对于每个程序员都是必不可少的,本文主要介绍了python读取多类型文件夹中的文档内容,具有一定的参考价值,感兴趣的可以了解一下

突发奇想,想使用python读取多类型文件夹中的文档内容,在Python中,读取多类型文件夹中的文档内容通常涉及几个步骤:

  • 遍历文件夹以获取文件列表。
  • 根据文件扩展名判断文件类型。
  • 使用适当的库或方法来读取每种文件类型的内容。

以下是一个简单的示例,展示如何使用Python读取一个文件夹中所有.txt.docx文件的内容:

首先,你需要安装python-docx库来读取.docx文件。你可以使用pip来安装:

pip install python-docx

然后,你可以使用以下Python脚本来读取文件夹中的文档内容:

import os
from docx import Document

def read_txt_file(file_path):
    with open(file_path, 'r', encoding='utf-8') as file:
        content = file.read()
    return content

def read_docx_file(file_path):
    doc = Document(file_path)
    content = '\n'.join([para.text for para in doc.paragraphs])
    return content

def read_folder_contents(folder_path):
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            file_path = os.path.join(root, file)
            if file_path.endswith('.txt'):
                content = read_txt_file(file_path)
                print(f"File: {file_path}")
                print(f"Content:\n{content}\n")
            elif file_path.endswith('.docx'):
                content = read_docx_file(file_path)
                print(f"File: {file_path}")
                print(f"Content:\n{content}\n")
            # 你可以根据需要添加更多文件类型的处理逻辑

# 使用示例
folder_to_read = 'path/to/your/folder'  # 替换为你的文件夹路径
read_folder_contents(folder_to_read)

这个脚本首先定义了读取.txt.docx文件的函数。然后,它遍历指定的文件夹,并根据文件扩展名调用相应的读取函数。对于每种文件类型,它都会打印文件名和内容。你可以根据需要添加更多文件类型的处理逻辑。

请注意,处理不同类型的文件(如PDF、Excel等)可能需要使用不同的库和方法。对于每种文件类型,你可能需要查找适当的Python库来读取其内容。

ps:补

1 读取Excel

通过pandas包来读取

data = pd.read_excel('data.xlsx', sheet_name="Sheet1", header = 1)  # header是第几行数据作为列名

2 读取csv文件

csv_data= pd.read_csv('/路径/文件名.csv')

3 读取txt文件

read_csv读取时会自动识别表头,数据有表头时不能设置header为空(默认读取第一行,即header=0);数据无表头时,若不设置header,第一行数据会被视为表头,应传入names参数设置表头名称或设置header=None。

data = pd.read_csv(r'stdout', sep='\t', header=0) # stdout是txt文件

到此这篇关于python读取多类型文件夹中的文档内容的文章就介绍到这了,更多相关python读取多类型文件内容内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/qq_36253366/article/details/137149626

延伸 · 阅读

精彩推荐