Python文件操作及与数据库的交互
一、文件操作
1. 打开文件
file = open('example.txt', 'r') # 以读模式打开文件
读模式 (r):只读文件,文件不存在会报错。 写模式 (w):写入文件,如果文件存在会清空内容。 追加模式 (a):在文件末尾追加内容,不会覆盖已有内容。
示例代码:读取文件并关闭
file = open('example.txt', 'r')content = file.read()print(content)file.close() # 记得用完之后关门关窗
2. 使用 with 上下文管理器
with open('example.txt', 'r') as file:content = file.read()print(content)# 这下不用担心忘关文件了,`with` 会自动处理
3. 写入文件
with open('example.txt', 'w') as file:file.write('Hello, World!')with open('example.txt', 'a') as file:file.write('\nAppending this line.')
4. 读取文件
with open('example.txt', 'r') as file:# 读取整个文件content = file.read()print(content)# 逐行读取file.seek(0) # 移动到文件开头line = file.readline()while line:print(line.strip()) # 去掉行末的换行符line = file.readline()# 读取所有行,返回一个列表file.seek(0)lines = file.readlines()print(lines)
5. 二进制文件操作
with open('image.jpg', 'rb') as file:binary_data = file.read()with open('copy.jpg', 'wb') as file:file.write(binary_data)
二、与数据库的交互
1. SQLite 数据库
连接数据库
import sqlite3conn = sqlite3.connect('example.db') # 如果数据库不存在会自动创建cursor = conn.cursor()
示例代码:创建表
cursor.execute('''CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY,name TEXT,age INTEGER)''')conn.commit() # 提交事务
插入数据
cursor.execute('''INSERT INTO users (name, age) VALUES (?, ?)''', ('Alice', 30))conn.commit()
查询数据
cursor.execute('SELECT * FROM users')rows = cursor.fetchall()for row in rows:print(row)
更新和删除数据
cursor.execute('UPDATE users SET age = ? WHERE name = ?', (31, 'Alice'))conn.commit()cursor.execute('DELETE FROM users WHERE name = ?', ('Alice',))conn.commit()
2. MySQL 数据库
安装 pymysql 库
连接 MySQL 数据库
import pymysqlconn = pymysql.connect(host='localhost',user='root',password='password',database='test_db')cursor = conn.cursor()
示例代码:创建表和插入数据
cursor.execute('''CREATE TABLE IF NOT EXISTS employees (id INT AUTO_INCREMENT PRIMARY KEY,name VARCHAR(100),salary FLOAT)''')conn.commit()cursor.execute('''INSERT INTO employees (name, salary) VALUES (%s, %s)''', ('Bob', 70000))conn.commit()
查询数据
cursor.execute('SELECT * FROM employees')rows = cursor.fetchall()for row in rows:print(row)
三、文件与数据库的交互
1. 文件数据导入数据库
import csvwith open('data.csv', 'r') as file:reader = csv.reader(file)for row in reader:cursor.execute('INSERT INTO users (name, age) VALUES (%s, %s)', row)conn.commit()
2. 数据库数据导出为文件
with open('output.csv', 'w', newline='') as file:writer = csv.writer(file)cursor.execute('SELECT * FROM users')writer.writerows(cursor.fetchall())
总结
目前,对编程、职场感兴趣的同学,大家可以联系我微信:golang404,拉你进入“程序员交流群”。
资料包含了《IDEA视频教程》、《最全python面试题库》、《最全项目实战源码及视频》及《毕业设计系统源码》,总量高达650GB。全部免费领取!全面满足各个阶段程序员的学习需求。