做一个简单的事:使用python读取一个txt文件,里面存储着N行用户id,需要一行行读取后再读取另一个存储用户昵称的txt文件,判断昵称是否有重复,如果没有重复就将数据库中的当前uid用户的昵称进行更换。本文地址:http://www.04007.cn/article/604.html,未经许可,不得转载.
使用python按行读取文本内容以及全部一次读取文本的实现方法如下:本文地址:http://www.04007.cn/article/604.html,未经许可,不得转载.
#按行读取方法1: f = open("data.txt","r") #读取第一行内容,包括换行符,可使用line[:-1]去掉换行符号,也可以使用.strip()来实现。 line = f.readline() line = line[:-1] #line = line.strip() while line: line = f.readline() line = line[:-1] f.close() #按行读取方法2: data = [] for line in open("data.txt","r"): data.append(line) #一次性全部读取方法1 f = open("data.txt","r") data = f.readlines() #直接将文件中按行读到list里 f.close() #一次性全部读取方法2 import numpy as np data = np.loadtxt("data.txt") #将文件中数据加载到data数组里 #为了方便,避免忘记close掉这个文件对象,可以用下面这种方式替代上面的open方法 with open('data.txt',"r") as f: str = f.read()实现的python脚本保存,以备后用:本文地址:http://www.04007.cn/article/604.html,未经许可,不得转载.
#!/usr/bin/python # -*- coding: utf8 -*- import MySQLdb import MySQLdb.cursors import sys import time reload(sys) sys.setdefaultencoding( "utf-8" ) #连接MYSQL def db_connection(): conn = MySQLdb.connect(host='192.168.1.11',db='database',user='user',passwd='passwd',port=3306,charset='utf8',cursorclass=MySQLdb.cursors.DictCursor) conn.autocommit(1) return conn #判断用户名是否存在 def checkUser(username): db_conn = db_connection() cursor=db_conn.cursor() cursor.execute("select uid from user_list where username='" + username + "'") return cursor.fetchone() #变更主表和分表用户数据 def updateUser(uid, username): db_conn = db_connection() cursor=db_conn.cursor() print "update user_list set username='" + username + "',password='e10adbe56e057f20f883ec3949ba59ab' where uid = " + uid cursor.execute("update user_list set username='" + username + "',password='e10adbe56e057f20f883ec3949ba59ab' where uid = " + uid) userid_fix = int(uid[-2:]) print "update user_"+ str(userid_fix) +" set username='" + username + "',password='e10adbe56e057f20f883ec3949ba59ab' where user_id = " + uid print ' -----|-------|----|-----|' cursor.execute("update user_"+ str(userid_fix) +" set username='" + username + "',password='e10adbe56e057f20f883ec3949ba59ab' where user_id = " + uid) #读取用户username数据 unames = open("user_data.txt") #取得用户ID列表 user_fp = open("id_data.txt") line = user_fp.readline().strip() count = 0 while line: uname = unames.readline().strip() if not uname: print 'user name is not enough' exit() data= checkUser(uname) while data: uname = unames.readline().strip() if not uname: print 'user name is not enough' exit() data= checkUser(uname) #print line + ' --> ' + uname updateUser(line, uname) count += 1; #getUser(line); #if(count>0): # user_fp.close() # exit() line = user_fp.readline().strip() user_fp.close() print '--------------success--------------' exit()本文地址:http://www.04007.cn/article/604.html,未经许可,不得转载.
本文地址:http://www.04007.cn/article/604.html 未经许可,不得转载. 手机访问本页请扫描右下方二维码.
![]() |
![]() |
手机扫码直接打开本页面 |