●7-1 理解文本文件和二进制文件的区别
textFile = open("7.1.txt","rt") #t 表示文本文件方式
print(textFile.readline())
textFile.close()
binFile = open("7-1.txt","rb") #r 表示二进制文件方式
print(binFile.readline())
binFile.close()
●7-2 文本文件逐行打印
fname = input("请输入要打开的文件: ")
fo = open(fname, "r")
for line in fo.readlines():
print(line)
fo.close()
●7-3 向文件写入一个列表
fname = input("请输入要写入的文件: ")
fo = open(fname, "w+")
ls = ["唐诗", "宋词", "元曲"]
fo.writelines(ls)
for line in fo:
print(line)
fo.close()
●7-4 GIF文件图像提取
from PIL import Image
im = Image.open('pybit.gif') # 读入一个GIF文件
try:
im.save('picframe{:02d}.png'.format(im.tell()))
while True:
im.seek(im.tell()+1)
im.save('picframe{:02d}.png'.format(im.tell()))
except:
print("处理结束")
●7-5 图像的颜色交换
from PIL import Image
im = Image.open('birdnest.jpg')
r, g, b = im.split()
om = Image.merge("RGB", (b, g, r))
om.save('birdnestBGR.jpg')
●7-6 图像的轮廓获取
from PIL import Image
from PIL import ImageFilter
im = Image.open('birdnest.jpg')
om = im.filter(ImageFilter.CONTOUR)
om.save('birdnestContour.jpg')
●7-7 图像的对比度增强
from PIL import Image
from PIL import ImageEnhance
im = Image.open('birdnest.jpg')
om = ImageEnhance.Contrast(im)
om.enhance(20).save('birdnestEnContrast.jpg')
●7-8 图像的字符画绘制
#e12.1DrawCharImage
from PIL import Image
ascii_char = list('"$%_&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-/+@<>i!;:,\^`.')
def get_char(r, b, g, alpha=256):
if alpha == 0:
return ' '
gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b)
unit = 256 / len(ascii_char)
return ascii_char[int(gray//unit)]
def main():
im = Image.open('astro.jpg')
WIDTH, HEIGHT = 100, 60
im = im.resize((WIDTH, HEIGHT))
txt = ""
for i in range(HEIGHT):
for j in range(WIDTH):
txt += get_char(*im.getpixel((j, i)))
txt += '\n'
fo = open("pic_char.txt","w")
fo.write(txt)
fo.close()
main()
●7-9 导入CSV格式数据到列表
fo = open("price2016.csv", "r")
ls = []
for line in fo:
line = line.replace("\n","")
ls.append(line.split(","))
print(ls)
fo.close()
●7-10 逐行处理CSV格式数据
fo = open("price2016bj.csv", "w")
ls = ['北京', '101.5', '120.7', '121.4']
fo.write(",".join(ls)+ "\n")
fo.close()
●7-11 一维数据写入CSV文件
fo = open("price2016.csv", "r")
ls = []
for line in fo:
line = line.replace("\n","")
ls = line.line.split(",")
lns = ""
for s in ls:
lns += "{}\t".format(s)
print(lns)
fo.close()
●7-12 二维数据写入CSV文件
fr = open("price2016.csv", "r")
fw = open("price2016out.csv", "w")
ls = []
for line in fr: #将CSV 文件中的二维数据读入到列表变量
line = line.replace("\n","")
ls.append(line.split(","))
for i in range(len(ls)): #遍历列表变量计算百分数
for j in range(len(ls[i])):
if ls[i][j].replace(".","").isnumeric():
ls[i][j] = "{:.2}%".format(float(ls[i][j])/100)
for row in ls: #将列表变量中的二位数据输出到CSV 文件
print(row)
fw.write(",".join(row)+"\n")
fr.close()
fw.close()
●7-13 CSV格式的HTML展示
#e13.1csv2html.py
seg1 = '''
<!DOCTYPE HTML>\n<html>\n<body>\n<meta charset=gb2312>
<h2 align=center>2016年7月部分大中城市新建住宅价格指数</h2>
<table border='1' align="center" width=70%>
<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></tr>\n'.format(*locls)
return seg
fr = open("price2016.csv", "r")
ls = []
for line in fr:
line = line.replace("\n","")
ls.append(line.split(","))
fr.close()
fw = open("price2016.html", "w")
fw.write(seg1)
fw.write('<th width="25%">{}</th>\n<th width="25%">{}</th>\n<th width="25%">{}</th>\n<th width="25%">{}</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()
●7-14 CSV格式向JSON格式的转换
#14.1csv2json.py
import json
fr = open("price2016.csv", "r")
ls = []
for line in fr:
line = line.replace("\n","")
ls.append(line.split(','))
fr.close()
fw = open("price2016.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, ensure_ascii=False)
fw.close()
● 7-15 JSON格式向CSV格式的转换
#14.2json2csv.py
import json
fr = open("price2016.json", "r")
ls = json.load(fr)
data = [ list(ls[0].keys()) ]
for item in ls:
data.append(list(item.values()))
fr.close()
fw = open("price2016_from_json.csv", "w")
for item in data:
fw.write(",".join(item) + "\n")
fw.close()