基于python读写各类文件

[toc]

本篇文章主要记录使用python读写各种格式的文件的方法,和其中一些常用的函数,一般都需要安装相应的库进行操作。由于时间问题,目前会在遇到需要使用python读写文件时顺便更新。

txt

对txt进行操作一般不需要安装额外的函数库。通常用python自带的open打开即可

1.读文件常用命令:

fp = open(case.txt, r) #打开文本文件,可读状态
str = fp.read() #读取整个文件
fp.close() #关闭文件,调用完就关闭是个好习惯

#按行读取方法1
while 1:
    str = fp.readline()  #按行读取数据
    str = str.strip('\n') #删除最后的换行符

#按行读取方法2
data = []
for line in open(case.txt,r): #line每次读取case.txt中的一行
    data.append(line) #存入data列表中

#按行读取方法3
fp = open(case.txt,r)
 #效果与方法2一样
data = fp.readlines()
fp.close

2.写文件常用命令:

fp = open(case.txt,w) #打开文本文件,可写入状态
fp.write(str) #写入数据,需要str类型
fp.close()

#列表写入文件
data = ['a', 'b', 'c']
with open(case.txt,w) as fp:
    fp.writelines(data) #写入列表数据
    fp.write('\n')

具体总结可查看:

https://www.cnblogs.com/hackpig/p/8215786.html

图片

通常使用pillow库进行操作

安装命令:

pip install pillow

pillow库比较常用的模块有两个,ImageImageDraw

Image

常用命令

from PIL import Image
pic = Image.new(RGB,(width, height), (255, 255, 255)) #新建一个图片文件
#不写颜色数据则默认为(0, 0, 0)

pic = Image.open(data.png) #打开一个图片文件
pic = Image.open(data.png).convert(L) #以灰度模式打开一个图片文件

width, height = pic.size #获取图片的宽高
pic.putpixel((x,y),(100, 100, 100)) #对(x,y)坐标的像素点填充颜色,左上角坐标为(0, 0)

pic.show() #用默认图片软件展示图片
pic.save() #保存图片,可写路径,默认与python文件同路径

其它命令

从一张图片中提取一部分:

pic_1 = pic.crop((x1,y1,x2,y2)) # x1 y1为左上角坐标,x2 y2为右下角坐标

#将一张图片分成很多块并保存:
a = 30
b = 45
for x in range(80):
    for y in range(80):
        box = (x*a, y*b, (x+1)*a, (y+1)*b)
 #每片碎片为30*45
        f = image.crop(box)
 #image为原图
        f.save(./crop/%s.png % ran()) #ran()为一个自定义随机命名函数,保存在crop文件夹下

ImageDraw

from PIL import ImageDraw
pic = Image.new(RGB,(width, height),(0,0,0))
draw = ImageDraw.ImageDraw(pic)  #创建绘画对象

可选参数:
fill = fillColor ,填充颜色
outline = outlineColor , 边框颜色

draw.rectangle((x1,y1,x2,y2),fill = (255,255,255),outline = (0,0,0))
#画一个矩形,必填参数为坐标,第一第二个为起始点坐标,第三第四个为终点坐标
draw.text((10, 10), Hello, fill=(255,0,0), font=None) #画文字,文本左上角为x y坐标数据

draw.line(((60,60),(90,60))) #画一条直线
draw.line(((60,60),(90,60), (90,90), (60,90), (60,60))) 
#画多条直线,每条线的起点坐标就是上一条线的终点坐标,此例子就是4条直线围成一个正方形

具体总结可查看:

https://blog.csdn.net/leemboy/article/details/83792729

https://blog.csdn.net/wuguangbin1230/article/details/80348504

https://www.cnblogs.com/wei-li/archive/2012/04/19/2456725.html

zip压缩包

通常使用zipfile

zipfile库中最常用的两个模块是ZipFile和Zipinfo

ZipFile常用命令:

import zipfile
f = zipfile.ZipFile(case.zip,'r') #以可读方式创建一个ZipFile对象
f_name = f.namelist() #获取zip对象内所有文件的名称列表
f_info = f.getinfo(name) #获取zip对象内指定文件的信息
f_infolist = f.infolist() #获取zip对象内所有文件的信息,返回列表
f.extract(name, path, pwd) #解压zip对象内指定文件到指定路径中,密码为pwd
f.printdir() #将zip对象内的信息打印到控制台上

Zipinfo常用命令:

import zipfile, os
zipFile = zipfile.ZipFile(os.path.join(os.getcwd(), 'duoduo.zip'))
zipInfo = zipFile.getinfo('name') #zip对象内的文件
print ('filename:', zipInfo.filename)  #获取文件名称
print ('date_time:', zipInfo.date_time)   #获取文件最后修改时间。返回一个包含6个元素的元组:(年, 月, 日, 时, 分, 秒)
print ('compress_type:', zipInfo.compress_type) #压缩类型
print ('comment:', zipInfo.comment)   #文档说明
print ('extra:', zipInfo.extra)    #扩展项数据
print ('create_system:', zipInfo.create_system) #获取创建该zip文档的系统。
print ('create_version:', zipInfo.create_version) #获取 创建zip文档的PKZIP版本。
print ('extract_version:', zipInfo.extract_version) #获取 解压zip文档所需的PKZIP版本。
print ('extract_version:', zipInfo.reserved) # 预留字段,当前实现总是返回0。
print ('flag_bits:', zipInfo.flag_bits) #zip标志位。
print ('volume:', zipInfo.volume) # 文件头的卷标。
print ('internal_attr:', zipInfo.internal_attr) #内部属性。
print ('external_attr:', zipInfo.external_attr) #外部属性。
print ('header_offset:', zipInfo.header_offset) # 文件头偏移位。
print ('CRC:', zipInfo.CRC) # 未压缩文件的CRC-32。
print ('compress_size:', zipInfo.compress_size) #获取压缩后的大小。
print ('file_size:', zipInfo.file_size) #获取未压缩的文件大小。
zipFile.close() 

具体总结可查看:

https://www.cnblogs.com/ManyQian/p/9193199.html

EXCEL表格

通常使用 openpyxl 库,安装命令:

pip install openpyxl

常用模块:

from openpyxl import load_workbook
from openpyxl import Workbook

当然还有其他模块,不过一般用的不多:

from openpyxl.styles import PatternFill, Border, Side, Alignment, Protection, Font, Color, Fill
from openpyxl.styles import colors
from openpyxl.formatting.rule import ColorScaleRule

创建文件

from openpyxl import Workbook 
# 实例化
wb = Workbook()
# 激活 worksheet
ws = wb.active

#创建表
# 方式一:插入到最后
ws1 = wb.create_sheet(sheet) 
# 方式二:插入到最开始的位置
ws2 = wb.create_sheet(sheet, 0)

打开文件

wb = load_workbook('hunka.xlsx')
ws = wb['sheet'] #选择表

print(wb.sheetnames) #显示所有表名

储存、获取数据

ws['A4'] = 4  #直接复制
ws.append([1, 2, 3]) #附加行

c = ws['A4'] #直接索引单元格
c = ws.cell('A4') #另一种索引方法
c = ws.cell(row = 4, column = 2) #利用行列索引单元格,比较容易进行for循环

width = ws.max_column
  #获取最大列
height = ws.max_row   #获取最大行

储存文件

wb.save('document.xlsx')

获取填充颜色信息

ws.cell(rows, columns).fill.fgColor.rgb

一道比赛时提取填充色的例子:

from openpyxl import load_workbook
from openpyxl import Workbook
from openpyxl.styles import PatternFill, Border, Side, Alignment, Protection, Font, Color, Fill
from openpyxl.styles import colors
from openpyxl.styles import Fill,fills
from openpyxl.formatting.rule import ColorScaleRule
from PIL import Image,ImageDraw

wb = load_workbook('hunka.xlsx')
ws = wb['img']

fp = open(value.txt,w)
for columns in range(1, ws.max_column + 1): #列
    for rows in range(1, ws.max_row + 1):  #行
        fp.write(str(rows) +   + str(columns) +  )
        fp.write(ws.cell(rows, columns).fill.fgColor.rgb[2:])
        #if ws.cell(rows, columns).value == None:
        #   fp.write('\n')
        #   continue
        #fp.write(ws.cell(rows, columns).value)
        fp.write('\n')
fp.close()

image = Image.new('RGB', (ws.max_column, ws.max_row), (255, 255, 255))
width = ws.max_column
height = ws.max_row
draw = ImageDraw.ImageDraw(image)
fp = open(color.txt,r)
while 1:
    s = fp.readline()
    if not s:
        break
    a = int(s.split(' ')[0]) - 1
    b = int(s.split(' ')[1]) - 1
    color = (int(s.split(' ')[2][0:2],16),int(s.split(' ')[2][2:4],16),int(s.split(' ')[2][4:6],16))
    draw.point((b,a),fill=color)
image.show()
print(width)
print(height)

#print(ws.max_row)
#print(ws.max_column)

具体总结可查看:

http://www.52codes.net/develop/shell/58896.html

发表评论