Python读写各类数据文件

Python 提供了多种强大的工具和库,可以轻松实现对各种类型文件的读写操作,满足不同场景的数据处理需求。常见的文件类型包括文本文件(txt)、表格文件(CSV、Excel)、结构化数据文件(JSON、YAML、XML)、二进制数据文件(Parquet)、数据库文件(SQLite),以及其他格式如日志文件(log)、压缩文件(ZIP)和PDF文件等。通过内置的 open 函数和标准库模块如 csvjsonsqlite3 等,以及第三方库如 pandasyamlfpdf 等,Python 能够快速实现对这些文件的读写操作。这种灵活性和多样性使得 Python 成为处理数据、开发应用和实现自动化工作的首选编程语言之一。

Python 读写 txt 文件
python 复制代码
# 写入 TXT 文件
with open('example.txt', 'w', encoding='utf-8') as file:
    file.write("你好,Python 文件读写示例!\n第二行内容。")

# 读取 TXT 文件
with open('example.txt', 'r', encoding='utf-8') as file:
    content = file.read()
    print(content)
Python 读写 CSV 文件
python 复制代码
import csv
# 写入 CSV 文件
with open('example.csv', 'w', newline='', encoding='utf-8') as file:
    writer = csv.writer(file)
    writer.writerow(["姓名", "年龄", "城市"])
    writer.writerow(["张三", 25, "北京"])
    writer.writerow(["李四", 30, "上海"])

# 读取 CSV 文件
with open('example.csv', 'r', encoding='utf-8') as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)
Python 读写 Excel 文件
python 复制代码
import pandas as pd
# 写入 Excel 文件
data = {'姓名': ['张三', '李四'], '年龄': [25, 30], '城市': ['北京', '上海']}
df = pd.DataFrame(data)
df.to_excel('example.xlsx', index=False)

# 读取 Excel 文件
df_read = pd.read_excel('example.xlsx')
print(df_read)
Python 读写 JSON 文件
python 复制代码
import json
# 写入 JSON 文件
data = {'name': '张三', 'age': 25, 'city': '北京'}
with open('example.json', 'w', encoding='utf-8') as file:
    json.dump(data, file, ensure_ascii=False, indent=4)

# 读取 JSON 文件
with open('example.json', 'r', encoding='utf-8') as file:
    data_read = json.load(file)
    print(data_read)
Python 读写 SQLite 数据库
python 复制代码
import sqlite3
# 创建 SQLite 数据库并写入数据
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)")
cursor.execute("INSERT INTO users (name, age) VALUES (?, ?)", ('张三', 25))
conn.commit()

# 读取 SQLite 数据库数据
cursor.execute("SELECT * FROM users")
rows = cursor.fetchall()
for row in rows:
    print(row)
conn.close()
Python 读写 XML 文件
python 复制代码
import xml.etree.ElementTree as ET
# 写入 XML 文件
root = ET.Element("root")
user = ET.SubElement(root, "user")
ET.SubElement(user, "name").text = "张三"
ET.SubElement(user, "age").text = "25"
tree = ET.ElementTree(root)
tree.write("example.xml", encoding='utf-8', xml_declaration=True)

# 读取 XML 文件
tree = ET.parse('example.xml')
root = tree.getroot()
for elem in root.iter():
    print(elem.tag, elem.text)
Python 读写 Parquet 文件
python 复制代码
import pandas as pd
# 写入 Parquet 文件
data = {'姓名': ['张三', '李四'], '年龄': [25, 30], '城市': ['北京', '上海']}
df = pd.DataFrame(data)
df.to_parquet('example.parquet', index=False)

# 读取 Parquet 文件
df_read = pd.read_parquet('example.parquet')
print(df_read)
Python 读写 YAML 文件
python 复制代码
import yaml
# 写入 YAML 文件
data = {'姓名': '张三', '年龄': 25, '城市': '北京'}
with open('example.yaml', 'w', encoding='utf-8') as file:
    yaml.dump(data, file, allow_unicode=True)

# 读取 YAML 文件
with open('example.yaml', 'r', encoding='utf-8') as file:
    data_read = yaml.safe_load(file)
    print(data_read)
Python 读写 INI 文件
python 复制代码
import configparser
# 写入 INI 文件
config = configparser.ConfigParser()
config['DEFAULT'] = {'Server': 'localhost', 'Port': '8080'}
with open('example.ini', 'w', encoding='utf-8') as configfile:
    config.write(configfile)

# 读取 INI 文件
config.read('example.ini', encoding='utf-8')
print(dict(config['DEFAULT']))
Python 读写 PDF 文件
python 复制代码
from fpdf import FPDF
from PyPDF2 import PdfReader
# 写入 PDF 文件
pdf = FPDF()
pdf.add_page()
pdf.set_font('Arial', size=12)
pdf.cell(200, 10, txt="Python PDF 文件", ln=True, align='C')
pdf.output("example.pdf")

# 读取 PDF 文件
reader = PdfReader("example.pdf")
for page in reader.pages:
    print(page.extract_text())
Python 读写 ZIP 文件
python 复制代码
import zipfile
# 写入 ZIP 文件
with zipfile.ZipFile('example.zip', 'w') as zipf:
    zipf.write('example.txt')

# 解压 ZIP 文件
with zipfile.ZipFile('example.zip', 'r') as zipf:
    zipf.extractall('output')
Python 读写 Log 文件
python 复制代码
import logging
# 写入日志
logging.basicConfig(filename='example.log', level=logging.INFO, format='%(asctime)s - %(message)s')
logging.info("这是一个日志信息")
logging.warning("这是一个警告信息")
logging.error("这是一个错误信息")

# 读取日志
with open('example.log', 'r', encoding='utf-8') as file:
    logs = file.read()
    print(logs)
相关推荐
Rust语言中文社区8 小时前
【Rust日报】 丰田“先锋”选择了 Rust
开发语言·后端·rust
邹小邹-AI8 小时前
Rust + 前端:下一个十年的“王炸组合”
开发语言·前端·rust
ECT-OS-JiuHuaShan8 小时前
否定之否定的辩证法,谁会不承认?但又有多少人说的透?
开发语言·人工智能·数学建模·生活·学习方法·量子计算·拓扑学
東雪木8 小时前
变量与数据类型
java·开发语言
Lisonseekpan8 小时前
Java分词器深度评测与实战指南
java·开发语言·后端
c***87198 小时前
Flask:后端框架使用
后端·python·flask
百***35489 小时前
JavaScript在Node.js中的集群部署
开发语言·javascript·node.js
光影少年9 小时前
node.js和nest.js做智能体开发需要会哪些东西
开发语言·javascript·人工智能·node.js
xu_yule9 小时前
Linux_14(多线程)线程控制+C++多线程
java·开发语言·jvm
c***97989 小时前
PHP在内容管理中的模板引擎
开发语言·php