一、文件读写的读书笔记
1.文件类型:文本文件和二进制文件
文本文件有统一的字符编码,如txt文件;
二进制文件没有统一的字符编码,由0和1组成,如png格式的图片文件、avi格式的视频文件。
2.文件的打开与关闭
操作系统中的文件默认为存储状态,首先要打开文件
open(文件名,打开方式)
文件名最好使用绝对路径,你可采用复制这个文件,然后粘贴时就得到这个文件的绝对路径;
打开方式:(open函数默认采用'rt'(文本只读)模式)
3.文件的读写
4.文件内容写进方法
二、将excel文件转化为csv文件
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ import pandas as pd import numpy as np import matplotlib.pyplot as plt #df.to_excel('C:/Users/Asus/Desktop/1.xlsx',sheet_name='dfg') df=pd.read_excel('C:/Users/Asus/Desktop/Python_2.xlsx',index_col=None,na_values=['NA']) print(df) for i in range(len(df.index)): # print(df.iloc[i,1]) for j in range(1,len(df.columns)): if df.iloc[i,j]=='优秀': df.iat[i,j]=90 elif df.iloc[i,j]=='良好': df.iat[i,j]=80 elif df.iloc[i,j]=='合格': df.iat[i,j]=60 else: df.iat[i,j]=1 df.to_csv('C:/Users/Asus/Desktop/Python2.csv') print(df) |
看一下结果
原文件: 转化后:
三、将csv文件转化为html文件
# -*- c# -*- coding:utf-8 ''' This is a programe that can change csv into html.
''' segl=''' <!DOCTYPE HTML>\n<html>\n<body>\n<meta charset=gb2312> <h2 align=center>18信计2python成绩05潘巧妍</h2> <table border='1' align='center' width=100%> <tr bgcolor='orange'>\n''' seg2="</tr>\n" seg3="</table>\n</body>\n</html>" def fill_data(locls): seg='<tr><td align="center">{}</td><td align="center">\ {}</td><td align="center">{}</td><td align="center">\ {}</td><td align="center">{}</td><td align="center">\ {}</td></tr>\n'.format(*locls) return seg fr=open("C:/Users/Asus/Desktop/Python2.csv",'r',encoding='UTF-8') ls=[] for line in fr: line=line.replace("\n","") ls.append(line.split(",")) fr.close() fw=open("C:/Users/Asus/Desktop/Python1.html","w") fw.write(segl) fw.write('<th width="15%">{}</th>\n<th width="15%">{}</th>\n<th width="15%">{}</th>\n<th width="15%">{}</th>\n<th width="15%">{}</th>\n<th width="15%">{}</th>\n'.format(*ls[0])) fw.write(seg2) for i in range(len(ls)-1): fw.write(fill_data(ls[i+1])) fw.write(seg3) fw.close() |
结果:
csv文件: html文件:
四、将csv文件转换为json文件
# -*- c# -*- coding:utf-8 ''' This is a programe that can change csv into html.
''' import json fr=open('C:/Users/Asus/Desktop/Python2.csv','r',encoding='UTF-8') ls=[] for line in fr: line=line.replace("\n","") ls.append(line.split(',')) fr.close() fw=open('C:/Users/Asus/Desktop/Python2.json','w') for i in range(1,len(ls)): ls[i]=dict(zip(ls[0],ls[i])) json.dump(ls[1:],fw,sort_keys=True,indent=4) fw.close() |
结果: