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)自動化工作的首選編程語言之一。
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)文章
簡單快捷:NumPy入門教程的環(huán)境設(shè)置
NumPy是Python語言的一個(gè)擴(kuò)展程序庫,支持高階大量的維度數(shù)組與矩陣運(yùn)算,此外也針對數(shù)組運(yùn)算提供大量的數(shù)學(xué)函數(shù)庫,本教程是為那些想了解NumPy的基礎(chǔ)知識和各種功能的人準(zhǔn)備的,它對算法開發(fā)人員特別有用,需要的朋友可以參考下2023-10-10
python 實(shí)現(xiàn)交換兩個(gè)列表元素的位置示例
今天小編就為大家分享一篇python 實(shí)現(xiàn)交換兩個(gè)列表元素的位置示例,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-06-06
Python調(diào)用易語言動態(tài)鏈接庫實(shí)現(xiàn)驗(yàn)證碼功能
今天成功把易語言調(diào)用驗(yàn)證碼通殺的DLL在Python中成功調(diào)用了,心理美滋滋的,接著把我的經(jīng)驗(yàn)及示例代碼分享給大家,希望對大家有所幫助2021-08-08

