python如何读取全部的文件

读取文本文件用open()函数,CSV文件推荐pandas库,JSON文件使用json模块,批量读取可用glob模块匹配文件。

在Python中读取全部文件,关键在于根据文件类型选择合适的模块和方法。下面介绍几种常见文件类型的读取方式。

读取文本文件(.txt)

使用内置的 open() 函数可以轻松读取纯文本文件。

示例:

with open('example.txt', 'r', encoding='utf-8') as file:
    content = file.read()
print(content)

说明:encoding 参数建议显式指定,避免中文乱码问题。

读取CSV文件

推荐使用 csv 模块或 pandas 库。

使用 pandas 示例:

import pandas as pd
df = pd.read_csv('data.csv')
print(df)

pandas 会将数据读成 DataFrame 结构,便于后续处理。

读取JSON文件

使用内置的 json 模块解析。

示例:

import json
with open('config.json', 'r', encoding='utf-8') as file:
    data = json.load(file)
print(data)

json.load() 直接将 JSON 文件转为 Python 字典或列表。

读取多个文件(批量读取)

如果需要读取目录下所有同类文件,可结合 osglob 模块。

示例:读取当前目录所有 .txt 文件

import glob
for filepath in glob.glob('*.txt'):
    with open(filepath, 'r', encoding='utf-8') as file:
        print(f"--- {filepath} ---")
        print(file.read())

glob.glob() 支持通配符匹配,方便批量操作。

基本上就这些。根据文件格式选择对应方法,注意编码和异常处理,就能稳定读取各类文件。