第一个网页

1. 文件读写笔记  

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

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

open('/Users/Ted/Desktop/test/abc.txt')   #绝对路径
2 open('abc.txt')    #相对路径
方法一:
file1 = open('/Users/Ted/Desktop/test/abc.txt','r',encoding='utf-8') 
filecontent = file1.read()            
print(filecontent)
file1.close()
方法二:
with open('/Users/Ted/Desktop/test/abc.txt','r',encoding='utf-8') as file1:
content = file1.read()
print(content)

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

方法一:

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

方法二:
# 使用with关键字的写法
with open('abc.txt','a') as file1:
#with open('文件地址','读写模式') as 变量名:
#格式:冒号不能丢
file1.write('anything') 
#格式:对文件的操作要缩进
#格式:无需用close()关闭
读入excel:
import openpyxl,csv
wb = openpyxl.load_workbook('homwork_mark.xlsx')
sheet_mark = wb['Sheet1']

with open('finalmark.csv', 'w', encoding='gbk', newline='') as file1:
    writer = csv.writer(file1)

    for row in sheet_mark.rows:
        list_mark = [row[0]]
        for cell in row:
            if cell.value == '优秀':
                cell.value = 90
            elif cell.value == '良好':
                cell.value = 80
            elif cell.value == '合格':
                cell.value = 60
            elif cell.value == '不合格':
                cell.value = 0
            list_mark.append(cell.value)
        writer.writerow(list_mark)
        list_mark = []

转为html:

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 @ 2020-05-26 22:27  糖加灰先生  阅读(88)  评论(0)    收藏  举报