Python读写常用数据文件的示例详解!

Python读写常用数据文件的示例详解!

Python 提供了多种强大的工具和库,可以轻松实现对各种类型文件的读写操作,本文为大家整理了Python读写常用的那些数据文件的方法,希望对大家有所帮助。

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

 

Python 读写 txt 文件

1
2
3
4
5
6
7
8
# 写入 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 文件

 

1
2
3
4
5
6
7
8
9
10
11
12
13
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 文件

1
2
3
4
5
6
7
8
9
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 文件

1
2
3
4
5
6
7
8
9
10
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 数据库

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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 文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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 文件

1
2
3
4
5
6
7
8
9
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 文件

1
2
3
4
5
6
7
8
9
10
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 文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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 文件
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 文件

1
2
3
4
5
6
7
8
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 文件

1
2
3
4
5
6
7
8
9
10
11
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)

到此这篇关于Python读写常用数据文件的示例详解的文章就介绍到这了。

 

 

学习资料见知识星球。

以上就是今天要分享的技巧,你学会了吗?若有什么问题,欢迎在下方留言。

快来试试吧,小琥 my21ke007。获取 1000个免费 Excel模板福利​​​​!

更多技巧, www.excelbook.cn

欢迎 加入 零售创新 知识星球,知识星球主要以数据分析、报告分享、数据工具讨论为主;

Excelbook.cn Excel技巧 SQL技巧 Python 学习!

你将获得:

1、价值上万元的专业的PPT报告模板。

2、专业案例分析和解读笔记。

3、实用的Excel、Word、PPT技巧。

4、VIP讨论群,共享资源。

5、优惠的会员商品。

6、一次付费只需129元,即可下载本站文章涉及的文件和软件。

文章版权声明 1、本网站名称:Excelbook
2、本站永久网址:http://www.excelbook.cn
3、本网站的文章部分内容可能来源于网络,仅供大家学习与参考,如有侵权,请联系站长王小琥进行删除处理。
4、本站一切资源不代表本站立场,并不代表本站赞同其观点和对其真实性负责。
5、本站一律禁止以任何方式发布或转载任何违法的相关信息,访客发现请向站长举报。
6、本站资源大多存储在云盘,如发现链接失效,请联系我们我们会第一时间更新。

THE END
分享
二维码
< <上一篇
下一篇>>