python 文件操作(文本与控制台,excel与数据库)

一、文本文件操作

1.能调用方法的一定是对象,比如数值、字符串、列表、元组、字典,甚至文件也是对象,Python中一切皆为对象。

 

str1 = 'hello'
str2 = 'world'
str3 = ' '.join([str1,str2])
print(str3)

 

2.三种基本的文件操作模式:r(only-read)、w(only-write)、a(append)

对文件进行操作的流程:

     第一,建立文件对象。

     第二,调用文件方法进行操作。

     第三,不要忘了关闭文件。(文件不关闭的情况下,内容会放在缓存,虽然Python会在最后自动把内容读到磁盘,但为了以防万一,要养成关闭文件的习惯)

 

(1)r模式

只读模式read(逐字符读),readline(只能读取第一行代码,原理是读取到第一个换行符就停),readlines(readlines会把内容以列表的形式输出

f = open('file','r')
f_read = f.read()  

#f_read = f.readline()  
print(f_read)
f.close()


f = open('file','r')

f_read = f.readlines()  
for i in f_read:
    print(i)
f.close()

 

(2)w模式和a模式

只写模式,在进行操作前,文件中所有内容会被清空。比如在file1中写入'hello world',程序执行后file1中就只剩下一句'hello world'

f = open('file','w',encoding='utf8')  #由于Python3的默认编码方式是Unicode,所以在写入文件的时候需要调用utf8,以utf8的方式保存,这时pycharm(默认编码方式是utf8)才能正确读取,当读取文件时,文件是utf8格式,pycharm也是utf8,就不需要调用了。
#f = open('file','a',encoding='utf8')
f_w = f.write('hello world')#返回写入的字符数 print(f_w) f.close()

追加模式,与w模式不同的是,a模式不会把原来内容清空,而是光标移到内容最后位置,继续写入新内容。比如在最后追加'hello world',只写模式和追加模式的不同在于写入操作开始时是否先删除原来的内容

 

3.文件操作某些方法

  • tell:查询文件中光标位置
  • seek:光标定位
  • flush 同步将数据从缓存转移到磁盘,马上写入
  • truncate 截断

不能是r模式下执行,

w模式下,已经清空所有数据,使用truncate没有任何意义,

a模式下,截断指定位置后的内容。

f = open('file','a')
f.truncate(6) #只显示6个字节的内容(6个英文字符或三个汉字),后面的内容被清空。

 

4.三种复杂读写模式:r+、w+、a+

      r+:读写模式,光标默认在起始位置,当需要写入的时候,光标自动移到最后

     w+:写读模式,先清空原内容,再写入,也能够读取

     a+:追加读模式,光标默认在最后位置,直接写入,也能够读取。

5.with和修改文件内容

 

#修改,同时打开两个文件,一个用迭代器的方法读,一个写
num = 0 with open('file','r') as f1,open('file2','w',encoding='utf8') as f2:#with不用关闭文件 for line in f1: num += 1 if num == 5: line = ''.join([line.strip(),'hi']) f2.write(line)

 二、excels文件操作

1、从数据库中读取插入到excel中

 pymsql模块连接mysql数据库,然后通过游标cursor查询SQL语句将结果存储在Excel文件中,其中Excel的生成使用xlwt

import pymysql
import xlwt
import datetime
def toexcel():
    #连接mysql数据库。
    conn = pymysql.connect(host='127.0.0.1', port=3306, user='xxx', passwd='xxx', db='xxx', charset='utf8')
    #使用cursor()方法获取操作游标。
    cursor = conn.cursor()
    #effect_row = cursor.execute("select a.username,count(if(b.ntype='18060',true,null)),count(if(b.ntype='1001',true,null)) from nctermnetlog_if_201803 a,ncsnettype b where a.nettype=b.ntype and stime>unix_timestamp('2018-03-18 09:00:00') group by a.username")
    #使用execute方法执行SQL语句,并将统计结果存储在effect_row变量中。
    effect_row = cursor.execute("select a.username,a.mac,count(if(b.ntype='18060',true,null)),count(if(b.ntype='1001',true,null)),count(if(b.ntype='18079',true,null)),count(if(b.ntype='18080',true,null)),count(if(b.ntype='7633',true,null)),count(if(b.ntype='21368',true,null)),count(if(b.ntype='21400',true,null)),count(if(b.ntype='23581',true,null)),count(if(b.ntype='21416',true,null)) from nctermnetlog_if_201803 a,ncsnettype b where a.nettype=b.ntype and stime>unix_timestamp('2018-03-21 00:00:00') and stime<unix_timestamp('2018-03-22 00:00:00') group by a.username")
    print effect_row  #打印总行数
    #获取所有的记录结果
    row_3 = cursor.fetchall()
    #print row_3  #打印统计结果
    #获取上述SQL语句中的检索条件名称(将要成为Excel第一行的表头)。
    fields = cursor.description
    #将字段写入到EXCEL新表的第一行 。
    workbook = xlwt.Workbook(encoding='utf-8')
    #创建Excel中的一个sheet,并命名且为可重写状态。
    sheet = workbook.add_sheet('result_count',cell_overwrite_ok=True)
    #构造一个列表VnameList,用于将上述表头重命名,一定要一一对应。
    VnameList = [u"用户名","MAC",u"微信ID","QQ",u"新浪微博",u"腾讯微博",u"腾讯视频",u"京东商城",u"淘宝",u"今日头条",u"美团"]
    #将上述list中的虚拟身份依次填入Excel中去。
    for field in range(0,len(VnameList)):
    #sheet.write(0,field,fields[field][0])
    sheet.write(0,field,VnameList[field].encode("utf-8"))

    #根据横纵坐标依次录入查询到的信息值。
    row = 1
    col = 0
    for row in range(1,len(row_3)+1):
        for col in range(0,len(fields)):
            sheet.write(row,col,u'%s'%row_3[row-1][col])
    #格式化时间输出,用于给Excel起名时使用。
    sheet_time = datetime.datetime.now()
    book_mark = sheet_time.strftime('%Y%m%d')
    #将Excel文件保存下来
    workbook.save('./name%s.xls'%book_mark.encode("utf-8"))
    #依次做提交和关闭操作。
    conn.commit()
    cursor.close()
    conn.close()

if __name__=="__main__":
    toexcel()

 

2、从excel读取插入到数据库中

 

import pymysql
import xlrd
import sys
'''
连接数据库
args:db_name(数据库名称)
returns:db
'''
def mysql_link(de_name):
    try:
        db = pymysql.connect(host="127.0.0.1", user="xxx",
        passwd="xxx",
        db=xxx,
        charset='utf8')
        return db
    except:
        print("could not connect to mysql server")
'''
读取excel函数
args:excel_file(excel文件,目录在py文件同目录)
returns:book
'''
def open_excel(excel_file):
    try:
        book = xlrd.open_workbook(excel_file) # 文件名,把文件与py文件放在同一目录下
        print(sys.getsizeof(book))
        return book
    except:
        print("open excel file failed!")
'''
执行插入操作
args:db_name(数据库名称)
table_name(表名称)
excel_file(excel文件名,把文件与py文件放在同一目录下)
'''
def store_to(db_name, table_name, excel_file):
    db = mysql_link(db_name) # 打开数据库连接
    cursor = db.cursor() # 使用 cursor() 方法创建一个游标对象 cursor
    book = open_excel(excel_file) # 打开excel文件
    sheets = book.sheet_names() # 获取所有sheet表名
    for sheet in sheets:
      sh = book.sheet_by_name(sheet) # 打开每一张表
      row_num = sh.nrows
      print(row_num)
      list = [] # 定义列表用来存放数据
      num = 0 # 用来控制每次插入的数量
      for i in range(1, row_num): # 第一行是标题名,对应表中的字段名所以应该从第二行开始,计算机以0开始计数,所以值是1
        row_data = sh.row_values(i) # 按行获取excel的值
        value = (row_data[0], row_data[1], row_data[2], row_data[3], row_data[4], row_data[5], \
        row_data[6], row_data[7], row_data[8], row_data[9], row_data[10], row_data[11], row_data[12],
        row_data[13], row_data[14])
        list.append(value) # 将数据暂存在列表
        num += 1
        if( num>= 100 ): # 每一百条数据执行一次插入
          print(sys.getsizeof(list))
          sql = "INSERT INTO " + table_name + " (time, xingbie, afdd, xzb, yzb, cfbj, jjlbmc, \
        bjlbmc, bjlxmc, bjlxxlmc, gxqymc,gxdwmc, afql, afxqxx, cjdwmc)\
        VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
          cursor.executemany(sql, list) # 执行sql语句
          num = 0 # 计数归零
          list.clear() # 清空list
          print("worksheets: " + sheet + " has been inserted 10000 datas!")
          print("worksheets: " + sheet + " has been inserted " + str(row_num) + " datas!")
          db.commit() # 提交
          cursor.close() # 关闭连接
          db.close()
if __name__ == '__main__':
    store_to('demo', 'demo_yangben', 'xxx.xlsx')

 

posted @ 2020-08-13 17:40  inhocho  阅读(20)  评论(0)    收藏  举报