自己的第一个网页

1. 文件读写笔记  

(1)读文件 :两种方式 ,用 open 或  with  open() as   ;  有三个参数: 路径,读写形式,编码方式 ,其中路径分为绝对路径和相对路径,py文件与被读取文件在同一文件夹时可用相对路径

    读取有三步:打开文件,读取文件,关闭文件 (用with open 时 可不用关闭文件)

1 open('/Users/Ted/Desktop/test/abc.txt')   #绝对路径
2 open('abc.txt')    #相对路径

方法一:

1 file1 = open('/Users/Ted/Desktop/test/abc.txt','r',encoding='utf-8') 
2 filecontent = file1.read()            
3 print(filecontent)
4 file1.close()

方法二:

1 with open('/Users/Ted/Desktop/test/abc.txt','r',encoding='utf-8') as file1:
2     content = file1.read()
3     print(content)

 

(2) 写文件原理同上,但需把第二个参数改为 ‘w’

方法一:

1 file1 = open('abc.txt','a') 
2 file1.write('nothing') 
3 file1.close()

 

方法二:

1 # 使用with关键字的写法
2 with open('abc.txt','a') as file1:
3 #with open('文件地址','读写模式') as 变量名:
4     #格式:冒号不能丢
5     file1.write('anything') 
6     #格式:对文件的操作要缩进
7     #格式:无需用close()关闭

 

2. 读入 excel 文件

 1 import openpyxl,csv
 2 wb = openpyxl.load_workbook('homwork_mark.xlsx')
 3 sheet_mark = wb['Sheet1']
 4 
 5 with open('finalmark.csv', 'w', encoding='gbk', newline='') as file1:
 6     writer = csv.writer(file1)
 7 
 8     for row in sheet_mark.rows:
 9         list_mark = [row[0]]
10         for cell in row:
11             if cell.value == '优秀':
12                 cell.value = 90
13             elif cell.value == '良好':
14                 cell.value = 80
15             elif cell.value == '合格':  
16                 cell.value = 60
17             elif cell.value == '不合格':
18                 cell.value = 0
19             list_mark.append(cell.value)
20         writer.writerow(list_mark)
21         list_mark = []    
22     

 

 

3. 转为 HTML文件

 1 seg1 = '''
 2 <!DOCTYPE HTML>\n<html>\n<body>\n<meta charset=utf-8>
 3 <h1 align=center>Python_1</h1>
 4 <table border='1' align="center" width=100%>
 5 <tr bgcolor='yellow'>\n'''
 6 seg2="</tr>\n"
 7 seg3="</table>\n</body>\n</html>"
 8 def fill_data(locls):
 9     seg = '<tr><td align="center">{}</td><td align="center">\
10     {}</td><td align="center">{}</td><td align="center">\
11     {}</td ><td align="center">{}</td></tr><td align="center">{}</td></tr>\n'.format(*locls)
12     return seg
13 fr = open("finalmark.csv","r",encoding='utf-8')
14 ls = []
15 for line in fr:
16     line = line.replace("\n","")
17     ls.append(line.split(","))
18 print(ls)
19 fr.close()
20 fw = open("finalmark_2.html","w",encoding='utf-8')
21 fw.write(seg1)
22 fw.write('<th width="10%">{}</th>\n<th width="10%">{}</th>\n<th width="10%">{}</th>\n<th width="10%">{}</th>\n<th width="10%">{}</th>\n<th width="10%">{}</th>\n'.format(*ls[0]))
23 fw.write(seg2)
24 for i in range(len(ls)-1):
25     fw.write(fill_data(ls[i+1]))
26 fw.write(seg3)
27 fw.close

 

 

posted on 2020-05-24 09:52  Hrunjie  阅读(175)  评论(0编辑  收藏  举报

导航