当前位置: 首页 > news >正文

用Python打开不同联类型的文件

        在 Python 中,你可以使用不同的模块来打开和处理各种类型的文件(如文本文件、CSV、Excel、JSON、PDF、数据库等)。以下是一些常见文件类型的处理方法,以及如何将它们读取到 pandas.DataFrame 中:

 一、文本文件(.txt)

1. 打开并读取内容

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

2. 写入内容

with open("example.txt", "w", encoding="utf-8") as file:file.write("Hello, world!")

二、CSV 文件(.csv)

1. 使用 pandas 读取(推荐)

import pandas as pd
df = pd.read_csv("example.csv")
print(df.head())

2. 手动读取(适用于简单解析)

import csv
with open("example.csv", newline="", encoding="utf-8") as csvfile:reader = csv.reader(csvfile)for row in reader:print(row)

✅ 注意:Excel 文件读取需要 openpyxlxlrd 作为引擎。

 四、JSON 文件(.json)

1. 读取 JSON 文件到 Python 字典

import json
with open("example.json", "r", encoding="utf-8") as f:data = json.load(f)print(data)

2. 将 JSON 数据读入 DataFrame(适用于结构化数据)

import pandas as pd
with open("example.json", "r", encoding="utf-8") as f:data = json.load(f)
df = pd.DataFrame(data)
print(df.head())

五、数据库文件(如 SQLite)

使用 sqlite3 读取 SQLite 数据库

import sqlite3
import pandas as pdconn = sqlite3.connect("example.db")
query = "SELECT * FROM table_name"
df = pd.read_sql(query, conn)
print(df.head())

 六、PDF 文件(.pdf)

使用 PyPDF2 读取 PDF 内容

pip install PyPDF2
import PyPDF2
with open("example.pdf", "rb") as file:reader = PyPDF2.PdfReader(file)for page in reader.pages:print(page.extract_text())

✅ 注意:PDF 内容提取可能受格式限制,复杂排版可能需要其他工具如 pdfplumberPyMuPDF

七、Word 文档(.docx)

使用 python-docx 读取 Word 文件

pip install python-docx
from docx import Document
doc = Document("example.docx")
for para in doc.paragraphs:print(para.text)

八、图像文件(.jpg / .png)

使用 Pillow 读取图像

pip install pillow
from PIL import Image
img = Image.open("example.jpg")
img.show()

九、XML 文件(.xml)

使用 xml.etree.ElementTree 解析 XML

import xml.etree.ElementTree as ET
tree = ET.parse("example.xml")
root = tree.getroot()
for child in root:print(child.tag, child.attrib)

十、从网络 API 获取数据(JSON 格式)

使用 requests 获取 JSON 数据

pip install requests
import requests
import pandas as pdresponse = requests.get("https://api.example.com/data")
data = response.json()
df = pd.DataFrame(data)
print(df.head())

🧩 小贴士:将文件数据转换为 DataFrame

文件类型转换方法
CSVpd.read_csv()
Excelpd.read_excel()
JSONpd.DataFrame(data)
SQLpd.read_sql()
APIpd.DataFrame(response.json())

📌 总结

文件类型推荐模块是否支持 DataFrame
.txt内置 open()
.csvpandas / csv
.xlsxpandas + openpyxl
.jsonjson / pandas
.dbsqlite3 / pandas
.pdfPyPDF2 / pdfplumber
.docxpython-docx
.jpgPillow
.xmlxml.etree.ElementTree
APIrequests + pandas

http://www.dtcms.com/a/226108.html

相关文章:

  • 深入理解享元模式:用Java实现高效对象共享
  • Python中scapy库详细使用(强大的交互式数据包操作程序和库)
  • 思科设备网络实验
  • Python数据类型详解:从字符串到布尔值,一网打尽
  • 《机器学习数学基础》补充资料:韩信点兵与拉格朗日插值法
  • sqli-labs靶场32-37关(宽字节注入)
  • hot100 -- 5.普通数组系列
  • 机器学习算法-k-means
  • 02.上帝之心算法用GPU计算提速50倍
  • python库 PyYAML 详细使用
  • 【算法题】算法一本通
  • android stdio 的布局属性
  • 《Python语言程序设计》2018 第4章第9题3重量和价钱的对比,利用第7章的概念来解答你
  • 初学c语言22(编译和链接)
  • Day09
  • day62—DFS—太平洋大西洋水流问题(LeetCode-417)
  • 解决 IDEA 在运行时中文乱码问题
  • 第十一讲 | 多态
  • 构建系统maven
  • 实验:基于SpringBoot+MyBatis-Plus实现文章列表增删改查
  • 怎么更改cursor chat中的字体大小
  • 【Oracle】安装单实例
  • 上位机知识篇---网络类型
  • res.json() vs res.send() 的区别
  • Java内存区域与内存溢出异常分析与解决
  • linux命令 systemctl 和 supervisord 区别及用法解读
  • 卷积神经网络(CNN)完全指南:从原理到实战
  • ESP32基础知识1:项目工程建立和烧录
  • 分类预测 | Matlab实现CNN-LSTM-Attention高光谱数据分类
  • 操作系统学习(十)——文件系统