Python-22-file文件读取

ぃ、小莉子 提交于 2019-11-26 19:50:12
  1. 打开和关闭文件-open

    with可以自动关闭管道

     with open('','r') as fp:
     pass
    

    不用with,需要关闭

     file=open('','r') # 建立管道
     content=file.read() # 读入数据
     file.close() # 关闭管道
    
  2. 文件如果找不到

     #【文件读取,若文件不存在则报错】
     with open('datas/test.txt','rb') as fp:
         data=fp.read()
         print(data)
         data_str=data.decode(encoding='UTF-8')
         print(data_str)
     
     #【文件写入,若文件不存在就新建文件】
     with open('datas/test_input.txt', 'wb') as fp:
         fp.write('写入文件'.encode(encoding='UTF-8'))
    
  3. open()参数

    • filename
    • mode:r、w、a、rb、wb、ab
    • buffer:为0不缓存,为1缓存,为正是缓存区大小,为负是系统默认的大小
    • encoding:utf-8(8为最小位数,即英文一个字节,8bit)
  4. readline和readlines

     #fp自带迭代器
     with open('datas/test.txt','r',encoding='utf-8') as fp:
         #readline()-读一行,为string类型
         while 1:
             line = fp.readline()
             print(line)
             if not line:
                 break
     with open('datas/test.txt', 'r', encoding='utf-8') as fp:
         # readlines()-读多行,为list类型
         datas=fp.readlines()
         print(type(datas),datas)
    
  5. tell()

     fp.tell()--文件光标当前位置,即获取当前文件读取指针的位置
    
  6. seek()

    seek(x,0):从起始位置往后移动x个字符
    seek(x,1):从当前位置往后移动x个字符
    seek(-x,2):从结尾往前移动x个字符
    ps:在文本文件中,没有使用b模式选项打开的文件,只允许从文件头开始计算相对位置,从文件尾计算时就会引发异常。

     with open('datas/test.txt', 'r', encoding='utf-8') as fp:
     fp.seek(3,0) # 从开始移动3个字符
     data=fp.read()
     print(data)
     #
     with open('datas/test.txt', 'rb') as fp:
     fp.seek(-3,2)# 从结尾往前移动3个字符
     data=fp.read()
     print(data)
    
  7. json序列化

     users=[{"id":"001","name":"python"},{"id":"002","name":"语言"}]
     import json
     #1.dict->str
     str_users=json.dumps(users,ensure_ascii=True)
     #2.str->dict(序列化)
     json_users=json.loads(str_users,encoding='utf-8')
     
     with open('datas/users.json','w',encoding='UTF-8') as fp:
         json.dump(users,fp,ensure_ascii=True)
     
     with open('datas/users.json','r',encoding='UTF-8') as fp:
         u=json.load(fp)
         print(u[0])
    

    eval():也可序列化,但一般用法为:

     #1.
     print('1+2')
     print(eval('1+2'))
    
  8. excel:python读取excel依托于excel软件

    1. openpyxl模块

      1. 安装第三方:pip install openpyxl

      2. 使用openpyxl读取excel全部表,形成字典列表(从row=1,column=1开始)

        def read_excel_allsheet_dictlist_openpyxl():
             '''
             使用openpyxl读取excel全部表,形成字典列表
             :return 字典列表:
             '''
             from openpyxl import Workbook
             from openpyxl import load_workbook
             workbook_=load_workbook(u"datas/test_e.xlsx")
             sheet_names=workbook_.get_sheet_names()
             sheet_list=[]
             for sheeti in sheet_names:
                 table=workbook_.get_sheet_by_name(sheeti)
                 table_list=[]
                 for i in range(2,table.max_row+1):
                     table_dict={}
                     for j in range(1,table.max_column+1):
                         table_dict[table.cell(row=1,column=j).value]=table.cell(row=i,column=j).value
                     table_list.append(table_dict)
                 sheet_list.append({sheeti:table_list})
             return sheet_list
         print(read_excel_allsheet_dictlist_openpyxl())
        
      3. 使用openpyxl写入excel表并形成xlsx文件

         def write_excel_list_openpyxl():
             '''
             使用openpyxl将所给列表列表逐行写入excel中
             :return: 
             '''
             from openpyxl import Workbook
             from openpyxl import load_workbook
             from openpyxl.writer.excel import ExcelWriter
             rows=[
                 ['Number','data1','data2'],
                 [2,40],
                 [3,40,25],
                 [4,50,30]
             ]
             excel=Workbook()
             sheet=excel.create_sheet('Data',index=1)
             for row in rows:
                 sheet.append(row)
             excel.save(r'datas.xlsx')
         write_excel_list_openpyxl()
         
         def write_excel_dictlist_openpyxl():
             '''
             使用openpyxl将所给字典列表转换成列表列表写入excel
             :return: 
             '''
             from openpyxl import Workbook
             from openpyxl import load_workbook
             from openpyxl.writer.excel import ExcelWriter
             from utils.util import uid
             users=[
                 {'id': 1.0, 'name': 'iphone', 'price': 12000.0},
                 {'id': 2.0, 'name': 'vivo', 'price': 9000.0}
             ]
             rows=[]
             rows.append(list(users[0].keys()))
             for user in users:
                 rows.append(list(user.values()))
             excel=Workbook()
             sheet=excel.create_sheet('Data',index=1)
             for row in rows:
                 sheet.append(row)
             excel.save(r'{0}.xlsx'.format('datas_'+uid()))
         write_excel_dictlist_openpyxl()
        
    2. xlrd/xlwt

      1. 安装第三方:pip install xlrd pip install xlwt

      2. 使用xlrd读取excel全部表,形成字典列表(从row=0,column=0开始)

        def read_excel_allsheet_dictlist_xlrd():
              '''
             使用xlrd读取excel全部表,形成字典列表
             :return 字典列表:
             '''
             import xlrd
             workbook_=xlrd.open_workbook(u"datas/test_e.xlsx")
             sheet_names=workbook_.sheet_names()
             sheet_list=[]
             for tablei in sheet_names:
                 table=workbook_.sheet_by_name(tablei)
                 table_list=[]
                 for i in range(1,table.nrows):
                     dict={}
                     for j in range(table.ncols):
                         dict[table.row_values(0)[j]]=table.row_values(i)[j]
                     table_list.append(dict)
                 sheet_list.append({tablei:table_list})
             return sheet_list
         print(read_excel_allsheet_dictlist_xlrd())
        
      3. 使用xlwt写入excel表

         def write_excel_list_xlwt():
             '''
             使用xlwt将列表列表写入excel
             :return: 
             '''
             import xlwt
             from utils.util import uid
             rows=[
                 ['Number','data1','data2'],
                 [2,40],
                 [3,40,25],
                 [4,50,30]
             ]
             excel=xlwt.Workbook()
             sheet=excel.add_sheet('Data',cell_overwrite_ok=True)
             for i in range(len(rows)):
                 for j in range(len(rows[i])):
                     sheet.write(i,j,rows[i][j])
             excel.save(r'{0}.xlsx'.format('datas_xlwt_'+uid()))
         write_excel_list_xlwt()
        
  9. csv

    1. 用csv读取csv文件读取为字典列表

       def read_csv_to_dicts(field_names=None):
           import csv
           import json
           from collections import OrderedDict
           with open("datas/athlete_events.csv",'r',encoding='utf-8') as csv_file:
               header_line=csv_file.readline().replace(r'"','')
               headers=header_line.strip().split(',')
           with open('datas/athlete_events.csv','r',encoding='utf-8') as csv_file:
               reader=csv.DictReader(csv_file)
               datas=[]
               for row_dict in reader:
                   ordered_row_dict=OrderedDict()
                   if field_names:
                       for field in field_names:
                           ordered_row_dict[field]=row_dict[field]
                   else:
                       for field in headers:
                           ordered_row_dict[field]=row_dict[field]
                   datas.append(dict(ordered_row_dict))
               return datas
       print(read_csv_to_dicts())
      
    2. 用csv写入csv文件

       def writer_csv_dictlist():
           import csv
           users=[
               {'id': 1.0, 'name': 'iphone', 'price': 12000.0},
               {'id': 2.0, 'name': 'vivo', 'price': 9000.0}
           ]
           with open('datas/users2.csv','w') as fp:
               headers=users and list(users[0].keys())
               writer=csv.DictWriter(fp,fieldnames=headers)
               writer.writeheader()
               writer.writerows(users)
       writer_csv_dictlist()
      
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!