python 文件操作
1.pdf文件操作
PyPDF2这个库,可以轻松的处理pdf文件,它提供了读、写、分割、合并、文件转换等多种操作
属性和方法 | 描述 |
---|---|
getDestinationPageNumber(destination) | 检索给定目标对象的页码 |
getDocumentInfo() | 检索 PDF 文件的文档信息字典 |
getFields(tree = None,retval = None,fileObj= None) | 如果此 PDF 包含交互式表单字段,则提取字段数据, |
getFormTextFields() | 从文档中检索带有文本数据(输入,下拉列表)的表单域 |
getNameDestinations(tree = None,retval= None) | 检索文档中的指定目标 |
getNumPages() | 计算此 PDF 文件中的页数 |
getOutlines(node = None,outline = None,) | 检索文档中出现的文档大纲 |
getPage(pageNumber) | 从这个 PDF 文件中检索指定编号的页面 |
getPageLayout() | 获取页面布局 |
getPageMode() | 获取页面模式 |
getPageNumber(pageObject) | 检索给定 pageObject 处于的页码 |
getXmpMetadata() | 从 PDF 文档根目录中检索 XMP 数据 |
isEncrypted | 显示 PDF 文件是否加密的只读布尔属性 |
namedDestinations | 访问该getNamedDestinations() 函数的只读属性 |
现在我们将之前多个文件整合成一个文件
1.首先我们获取到pdf文件的名称,他们都是在aming目录下,并对他进行排序;
2.我们使用PyPDF2.PdfFileWriter()创建一个空白pdf文件;
3.使用PdfFileReader读取每个pdf文件;
4.使用addPage在空白pdf文件里面添加内容,使用getPage获取对应的文件内容;
5.在使用write方法保存文件
执行的结果为:
2.图片操作
image的方法
image.show()
image.open(file)
image.save(outputfile)
image.crop(left, upper, right, lower)#抠图
Image的几何处理:
out = im.resize((128, 128)) #调整图片大小
out = im.rotate(45) #逆时针旋转 45 度角。
out = im.transpose(Image.FLIP_LEFT_RIGHT) #左右对换。
out = im.transpose(Image.FLIP_TOP_BOTTOM) #上下对换。
out = im.transpose(Image.ROTATE_90) #旋转 90 度角。
out = im.transpose(Image.ROTATE_180) #旋转 180 度角。
out = im.transpose(Image.ROTATE_270) #旋转 270 度角。
执行结果为:
创建验证码图片
脚本为:
import random import string from PIL import Image, ImageFont, ImageDraw, ImageFilter font_path = "msyh.ttf" number = 4 size = (100, 30) bgcolor = (255, 255, 255) fontcolor = (0, 0, 255) linecolor = (255, 0, 0) draw_line = True # 加入干扰线条数的上下限 line_number = 30 #生成一个随机字符串 def getNumber(): source = list(string.ascii_letters) + list(string.digits) return "".join(random.sample(source, number)) #绘制干扰线 def getLine(draw, width, height): begin = random.randint(0, width), random.randint(0, height) end = random.randint(0, width), random.randint(0, height) draw.line([begin, end], fill=linecolor) def getCode(): width, height = size image = Image.new("RGBA", size, bgcolor) font = ImageFont.truetype(font_path, 25) draw = ImageDraw.Draw(image) text = getNumber() font_width, font_height = font.getsize(text) draw.text(((width - font_width) / 2, (height - font_height) / 2), text, font=font, fill=fontcolor) # 填充字符串 if draw_line: for i in range(line_number): getLine(draw, width, height) # image = image.transform((width + 20, height + 10), Image.AFFINE, (1, -0.3, 0, -0.1, 1, 0), Image.BILINEAR) # 创建扭曲 image = image.filter(ImageFilter.EDGE_ENHANCE_MORE) # 滤镜,边界加强 image.save('idencode.png') # 保存验证码图片 # image.show() if __name__ == '__main__': getCode()
执行结果为: