栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python处理text文件更新数据库

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python处理text文件更新数据库

打开文件

with open file as f: 这一习惯,即操作完毕后让其自动关闭文件。

with open("test.txt", "r") as f:  # 打开文件
    data = f.read()  # 读取文件
    print(data)
打开文件方式

file_path 为文件的路径
with open(file_path, ‘r’) as f_r:
r:只读方式打开文件,缺省默认。

with open(file_path, ‘w’) as f_w:
w:只写方式打开文件,若文件存在以覆盖方式写入,不存在则创建该文件(注意目录无法创建,即指定文件位置的目录不存在会报错)

其他方式选择:
r+:读写方式打开文件。
w+:读写方式代开文件,文件存在则覆盖写入。
a:追加方式打开文件,文件指针会放在文件结尾。
a+:追加读写。

python读取文件的三种方式:

read()
read(size)方法从文件当前位置起读取size个字节,默认(无参数)表示读取至文件结束为止,它的返回为字符串对象。
readline()
每次只读一行内容,读取时内存占用较少(适用于大文件),返回为字符串 对象。

with open("test.txt", "r") as f:
    data = f.readline()
    print(data)

readlines()
读取文件所有行,保存在列表(list)变量中,列表中每一行为一个元素,它返回的是一个列表对象。

with open("test.txt", "r") as f:
    data = f.readlines()
    print(data)

readlines 配套for循环,和 lins.strip使用

with open ("test.txt", 'r') as f:
	for line in f.readlines():
		line = line.strip('n') # 去掉换行符
		print(line)

案例演练:
创建文件 read.txt文件
编辑内容

Hello

空行

welcome to my world
空行

you are so clever !!!

import os

with open(os.path.join(os.getcwd(), 'read.txt')) as f:

content = f.read()

print(content)

print(type(content))

Hello

welcome to my world

you are so clever !!!

Process finished with exit code 0

import os
with open(os.path.join(os.getcwd(), 'read.txt')) as f:
while True:
	line = f.readline()
	if line:
		print(line)
	else:
		break

Hello

Process finished with exit code 0

import os
with open(os.path.join(os.getcwd(), 'read.txt')) as f:
while True:
	content = f.readlines()
	print(content)
	print(type(content))

[‘Hellon’, ‘welcome to my worldn’, ‘1234n’, ‘you are so clever
!!!’]

Process finished with exit code 0

其他辅助

seek: 用于移动文件读取指针到指定位置
itertools.islice() : 直接读取文件制定行

小tips总结:

读取文件前50行
for line in itertools.islice(f, 50):

跳过文件第一行读取文件
for line in itertools.islice(f, 1, None):

如果行数不存在,跳过,继续执行
if not line:
continue

写入text文本
with open("test.txt","w") as f:
    f.write("这是个测试!")  # 自带文件关闭功能,不需要再写f.close()
处理异常

Python使用 traceback.print_exc() 来代替print e 来输出详细的异常信息

traceback.print_exc() & raceback.format_exc() 区别
format_exc()返回字符串
print_exc()则直接给打印出来
两者效果是一样的

print_exc()还可以接受file参数直接写入到一个文件
traceback.print_exc(file=open(‘tb.txt’,‘w+’))

案例:

通过txt文件 更新 数据库内容

导包

import traceback
from itertools import islice
import pymysql
from dbutils.pooled_db import PooledDB

连接数据库配置

__config = {
    "host": "11.11.11.11",
    "port": 3306,
    "user": "name01",
    "password": "110",
    "database": "data1"
}

连接数据库

POOL = PooledDB(
    pymysql, 5,  # 连接池里的最少连接数
    **__config,
    setsession=['SET AUTOCOMMIT = 1']  # 设置线程池是否打开自动更新的配置
)
path = r"C:UsersAdministratorDesktoptest1.txt"
with open (path,,"r+") as f:
	for line in islice(f,1,None) # 跳过第一行,读取数据
		if not line:
			continue
		value = lines.replace('n','').split("|") #去除n换行,同时根据|将改行拆分成元组
		A = value[0] 元组第一个元素给A
		B = value[1] 元组第一个元素给B
		count = count + 1
		connection = POOL.connection() #连接池
		cursor = connection.cursor()#打开游标
		try:
			update_sql = 'UPDATE 表 set 字段1 = %s where 字段2 = %s'
			cursor.execute(update_sql,[A,B]) # 执行sql将字段1替换为A,条件这行数据的字段2等于B
			print(’处理个数 %d‘ % count)
		except:
			print(A)# 打印出出错的A
			traceback.print_exc() # 打印出报错原因
	cursor.close()#关闭游标
	connection.close()#关闭连接
split()讲解
str = "Line1-abcdef nLine2-abc nLine4-abcd";
print str.split( );       # 以空格为分隔符,包含 n
print str.split(' ', 1 ); # 以空格为分隔符,分隔成两个

[‘Line1-abcdef’, ‘Line2-abc’, ‘Line4-abcd’]
[‘Line1-abcdef’, ‘nLine2-abc nLine4-abcd’]

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/331303.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号