-
打开和关闭文件-open
with可以自动关闭管道
with open('','r') as fp: pass
不用with,需要关闭
file=open('','r') # 建立管道 content=file.read() # 读入数据 file.close() # 关闭管道
-
文件如果找不到
#【文件读取,若文件不存在则报错】 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'))
-
open()参数
- filename
- mode:r、w、a、rb、wb、ab
- buffer:为0不缓存,为1缓存,为正是缓存区大小,为负是系统默认的大小
- encoding:utf-8(8为最小位数,即英文一个字节,8bit)
-
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)
-
tell()
fp.tell()--文件光标当前位置,即获取当前文件读取指针的位置
-
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)
-
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'))
-
excel:python读取excel依托于excel软件
-
openpyxl模块
-
安装第三方:pip install openpyxl
-
使用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())
-
使用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()
-
-
xlrd/xlwt
-
安装第三方:pip install xlrd pip install xlwt
-
使用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())
-
使用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()
-
-
-
csv
-
用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())
-
用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()
-
来源:https://blog.csdn.net/qq_38328762/article/details/99072294