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

在Python中读取全部文件,关键在于根据文件类型选择合适的模块和方法。下面介绍几种常见文件类型的读取方式。
使用内置的 open() 函数可以轻松读取纯文本文件。
示例:<pre class="brush:php;toolbar:false;">with open('example.txt', 'r', encoding='utf-8') as file:
content = file.read()
print(content)
说明:encoding 参数建议显式指定,避免中文乱码问题。
推荐使用 csv 模块或 pandas 库。
立即学习“Python免费学习笔记(深入)”;
使用 pandas 示例:<pre class="brush:php;toolbar:false;">import pandas as pd
df = pd.read_csv('data.csv')
print(df)
pandas 会将数据读成 DataFrame 结构,便于后续处理。
使用内置的 json 模块解析。
示例:<pre class="brush:php;toolbar:false;">import json
with open('config.json', 'r', encoding='utf-8') as file:
data = json.load(file)
print(data)
json.load() 直接将 JSON 文件转为 Python 字典或列表。
如果需要读取目录下所有同类文件,可结合 os 或 glob 模块。
示例:读取当前目录所有 .txt 文件<pre class="brush:php;toolbar:false;">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() 支持通配符匹配,方便批量操作。
基本上就这些。根据文件格式选择对应方法,注意编码和异常处理,就能稳定读取各类文件。
以上就是python如何读取全部的文件的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号