python学习day21
一、csv文件读操作
1.创建reader
reader2 = csv.DictReader(open('files/北京高档酒店价格分析.csv', encoding='utf-8'))
for x in reader2:
scores = eval(f"{x['卫生评分']} + {x['服务评分']} + {x['设施评分']} + {x['位置评分']}")/4
print(x['\ufeff酒店名称'], scores)
二、csv文件写操作
1.创建writer
writer = csv.writer(open('files/学生信息.csv', 'w', encoding='utf-8', newline=''))
writer.writerow(['姓名', '性别', '年龄', '分数'])
writer.writerows([
['小明', '男', '18', '90'],
['小花', '女', '18', '88'],
['小马', '女', '20', '78']
])
writer2 = csv.DictWriter(open('files/学生信息2.csv', 'w', newline='', encoding='utf-8'),
['姓名', '性别', '年龄', '分数'])
writer2.writeheader()
writer2.writerow({'姓名': '小明', '性别': '男', '年龄': '18', '分数': 90})
writer2.writerows([
{'姓名': '小朱', '性别': '男', '年龄': '20', '分数': 90},
{'姓名': '小花', '性别': '女', '年龄': '18', '分数': 88},
{'姓名': '小马', '性别': '女', '年龄': '19', '分数': 78},
])
三、pdf文件操作
from PyPDF2 import PdfFileReader, PdfFileReader, PdfFileWriter
reader1 = PdfFileReader(open('files/美食分享.pdf', 'rb'))
reader2 = PdfFileReader(open('files/存储引擎的讲解.pdf', 'rb'))
page_num1 = reader1.numPages
page_num2 = reader2.numPages
page1 = reader1.getPage(0, )
page2 = reader1.getPage(1)
writer = PdfFileWriter()
writer.addPage(page1)
writer.addPage(page2)
writer.write(open('files/new.pdf', 'wb'))
练习
from PyPDF2 import PdfFileReader, PdfFileReader, PdfFileWriter
reader1 = PdfFileReader(open('files/美食分享.pdf', 'rb'))
reader2 = PdfFileReader(open('files/存储引擎的讲解.pdf', 'rb'))
page_num1 = reader1.numPages
page_num2 = reader2.numPages
writer = PdfFileWriter()
min_page = min(page_num1, page_num2)
for i in range(min_page):
writer.addPage(reader1.getPage(i))
writer.addPage(reader2.getPage(i))
for z in range(page_num2, page_num1):
writer.addPage(reader1.getPage(z))
writer.write(open('files/new2.pdf', 'wb'))
四、添加水印
from PyPDF2 import PdfFileReader, PdfFileReader, PdfFileWriter
import reportlab
water_reader = PdfFileReader(open('files/watermark.pdf', 'rb'))
file_reader = PdfFileReader(open('files/存储引擎的讲解.pdf', 'rb'))
water_page = water_reader.getPage(0)
page_num = file_reader.numPages
page1 = file_reader.getPage(0)
writer = PdfFileWriter()
for i in range(page_num):
file_reader.getPage(i).mergePage(water_page)
writer.addPage(file_reader.getPage(i))
writer.write(open('files/new_存储引擎的讲解.pdf', 'wb'))
五、创建水印文件
from PyPDF2 import PdfFileReader, PdfFileReader, PdfFileWriter
from reportlab.pdfgen import canvas
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
pdfmetrics.registerFont(TTFont('font1', 'files02/bb.ttf'))
pdfmetrics.registerFont(TTFont('font2', 'files02/青呱石头体.ttf'))
pdfmetrics.registerFont(TTFont('font3', 'files02/dd.ttf'))
pdf = canvas.Canvas('files02/water02.pdf')
pdf.rotate(45)
pdf.setFont('font3', 50)
pdf.setFillColorRGB(0, 0, 1, 0.5)
pdf.drawString(400, 100, '紫檀香')
pdf.save()
|