Python讀寫常用數(shù)據(jù)文件的示例詳解
Python 提供了多種強(qiáng)大的工具和庫,可以輕松實(shí)現(xiàn)對各種類型文件的讀寫操作,滿足不同場景的數(shù)據(jù)處理需求。常見的文件類型包括文本文件(txt)、表格文件(CSV、Excel)、結(jié)構(gòu)化數(shù)據(jù)文件(JSON、YAML、XML)、二進(jìn)制數(shù)據(jù)文件(Parquet)、數(shù)據(jù)庫文件(SQLite),以及其他格式如日志文件(log)、壓縮文件(ZIP)和PDF文件等。通過內(nèi)置的 open 函數(shù)和標(biāo)準(zhǔn)庫模塊如 csv、json、sqlite3 等,以及第三方庫如 pandas、yaml、fpdf 等,Python 能夠快速實(shí)現(xiàn)對這些文件的讀寫操作。這種靈活性和多樣性使得 Python 成為處理數(shù)據(jù)、開發(fā)應(yīng)用和實(shí)現(xiàn)自動(dòng)化工作的首選編程語言之一。
Python 讀寫 txt 文件
# 寫入 TXT 文件
with open('example.txt', 'w', encoding='utf-8') as file:
file.write("你好,Python 文件讀寫示例!\n第二行內(nèi)容。")
# 讀取 TXT 文件
with open('example.txt', 'r', encoding='utf-8') as file:
content = file.read()
print(content)
Python 讀寫 CSV 文件
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 文件
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 文件
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 數(shù)據(jù)庫
import sqlite3
# 創(chuàng)建 SQLite 數(shù)據(jù)庫并寫入數(shù)據(jù)
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 數(shù)據(jù)庫數(shù)據(jù)
cursor.execute("SELECT * FROM users")
rows = cursor.fetchall()
for row in rows:
print(row)
conn.close()
Python 讀寫 XML 文件
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 文件
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 文件
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 文件
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 文件
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 文件
import logging
# 寫入日志
logging.basicConfig(filename='example.log', level=logging.INFO, format='%(asctime)s - %(message)s')
logging.info("這是一個(gè)日志信息")
logging.warning("這是一個(gè)警告信息")
logging.error("這是一個(gè)錯(cuò)誤信息")
# 讀取日志
with open('example.log', 'r', encoding='utf-8') as file:
logs = file.read()
print(logs)到此這篇關(guān)于Python讀寫常用數(shù)據(jù)文件的示例詳解的文章就介紹到這了,更多相關(guān)Python讀寫數(shù)據(jù)文件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Pandas處理DataFrame稀疏數(shù)據(jù)及維度不匹配數(shù)據(jù)分析詳解
這篇文章主要為大家介紹了Pandas處理DataFrame稀疏數(shù)據(jù)及維度不匹配數(shù)據(jù)分析詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-02-02
Python實(shí)現(xiàn)讀取csv文件并進(jìn)行排序
這篇文章主要為大家詳細(xì)介紹了一個(gè)python簡單案例并進(jìn)行代碼展示,本文的案例是利用pandas庫實(shí)現(xiàn)讀取csv文件并按照列的從小到大進(jìn)行排序,需要的可以參考一下2023-02-02
Python Pip命令用法大全和技術(shù)應(yīng)用指南
這篇文章為大家詳細(xì)介紹了Python Pip的全面命令及其應(yīng)用,包括安裝,升級,依賴管理,虛擬環(huán)境管理,網(wǎng)絡(luò)代理等內(nèi)容,感興趣的小伙伴可以了解下2025-11-11
Pytorch使用PIL和Numpy將單張圖片轉(zhuǎn)為Pytorch張量方式
這篇文章主要介紹了Pytorch使用PIL和Numpy將單張圖片轉(zhuǎn)為Pytorch張量方式,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-05-05
解決Django響應(yīng)JsonResponse返回json格式數(shù)據(jù)報(bào)錯(cuò)問題
這篇文章主要介紹了解決Django響應(yīng)JsonResponse返回json格式數(shù)據(jù)報(bào)錯(cuò)問題,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-08-08

