第十周博客作业

一、文件读写的读书笔记

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()

 

结果:

转载于:https://www.cnblogs.com/panqiaoyan/p/10797829.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值