python 提供了多种强大的工具和库,可以轻松实现对各种类型文件的读写操作,满足不同场景的数据处理需求。常见的文件类型包括文本文件(txt)、表格文件(csv、excel)、结构化数据文件(json、yaml、xml)、二进制数据文件(parquet)、数据库文件(sqlite),以及其他格式如日志文件(log)、压缩文件(zip)和pdf文件等。通过内置的 open 函数和标准库模块如 csv、json、sqlite3 等,以及第三方库如 pandas、yaml、fpdf 等,python 能够快速实现对这些文件的读写操作。这种灵活性和多样性使得 python 成为处理数据、开发应用和实现自动化工作的首选编程语言之一。
python 读写 txt 文件
# 写入 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 文件
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 数据库
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 文件
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("这是一个日志信息") logging.warning("这是一个警告信息") logging.error("这是一个错误信息") # 读取日志 with open('example.log', 'r', encoding='utf-8') as file: logs = file.read() print(logs)
到此这篇关于python读写常用数据文件的示例详解的文章就介绍到这了,更多相关python读写数据文件内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论