Python学习笔记之 自动化办公与鼠标键盘模拟
读写csv文件
import csv
def readCsv(path):
infoList = []
with open(path, "r") as f:
allFileInfo = csv.reader(f)
for row in allFileInfo:
infoList.append(row)
return infoList
path = r"C:\Users\xlg\Desktop\Python-1704\day15\2、读写csv文件\000001.csv"
info = readCsv(path)
import csv
def writeCsv(path, data):
with open(path, "w") as f:
writer = csv.writer(f)
for rowData in data:
print("rowData = ", rowData)
writer.writerow(rowData)
path = r"C:\Users\xlg\Desktop\Python-1704\day15\2、读写csv文件\000002.csv"
writeCsv(path, [["1","2","3"],["4","5","6"],["7","8","9"]])
读取PDF文件
import sys
import importlib
importlib.reload(sys)
from pdfminer.pdfparser import PDFParser, PDFDocument
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import PDFPageAggregator
from pdfminer.layout import LTTextBoxHorizontal, LAParams
from pdfminer.pdfinterp import PDFTextExtractionNotAllowed
def readPDF(path, toPath):
#以二进制形式打开pdf文件
f = open(path, "rb")
#创建一个pdf文档分析器
parser = PDFParser(f)
#创建pdf文档
pdfFile = PDFDocument()
#链接分析器与文档对象
parser.set_document(pdfFile)
pdfFile.set_parser(parser)
#提供初始化密码
pdfFile.initialize()
#检测文档是否提供txt转换
if not pdfFile.is_extractable:
raise PDFTextExtractionNotAllowed
else:
#解析数据
#数据管理器
manager = PDFResourceManager()
#创建一个PDF设备对象
laparams = LAParams()
device = PDFPageAggregator(manager, laparams=laparams)
#解释器对象
interpreter = PDFPageInterpreter(manager, device)
#开始循环处理,每次处理一页
for page in pdfFile.get_pages():
interpreter.process_page(page)
layout = device.get_result()
for x in layout:
if (isinstance(x, LTTextBoxHorizontal)):
with open(toPath, "a") as f:
str = x.get_text()
#print(str)
f.write(str+"\n")
path = r"C:\Users\xlg\Desktop\Python-1704\day15\3、读取PDF文件\sunck.pdf"
toPath = r"C:\Users\xlg\Desktop\Python-1704\day15\3、读取PDF文件\n.txt"
readPDF(path, toPath)
读写word文件
import win32com
import win32com.client
def readWordFile(path):
#调用系统word功能,可以处理doc和docx两种文件
mw = win32com.client.Dispatch("Word.Application")
#打开文件
doc = mw.Documents.Open(path)
for paragraph in doc.Paragraphs:
line = paragraph.Range.Text
print(line)
#关闭文件
doc.Close()
#退出word
mw.Quit()
path = r"C:\Users\xlg\Desktop\Python-1704\day15\4、word自动化办公\sunck.doc"
readWordFile(path)
import win32com
import win32com.client
def readWordFileToOtherFile(path, toPath):
mw = win32com.client.Dispatch("Word.Application")
doc = mw.Documents.Open(path)
#将word的数据保存到另一个文件
doc.SaveAs(toPath, 2)#2表示为txt文件
doc.Close()
mw.Quit()
path = r"C:\Users\xlg\Desktop\Python-1704\day15\4、word自动化办公\sunck.doc"
toPath = r"C:\Users\xlg\Desktop\Python-1704\day15\4、word自动化办公\a.txt"
readWordFileToOtherFile(path, toPath)
import win32com
import win32com.client
import os
def makeWordFile(path, name):
word = win32com.client.Dispatch("Word.Application")
#让文档可见
word.Visible = True
#创建文档
doc = word.Documents.Add()
#写内容
#从头开始写
r = doc.Range(0, 0)
r.InsertAfter("亲爱的"+ name + "\n")
r.InsertAfter(" 我想你……\n")
#存储文件
doc.SaveAs(path)
#关闭文件
doc.Close()
#退出word
word.Quit()
names = ["张三", "李四", "王五"]
for name in names:
path = os.path.join(os.getcwd(), name)
makeWordFile(path, name)
读写Excel文件
# xlsx xls
# openpyxl -> xlsx
from openpyxl.reader.excel import load_workbook
def readXlsxFile(path):
#打开文件
file = load_workbook(filename=path)
#所有表格的名称
#print(file.get_sheet_names())
sheets = file.get_sheet_names()
#拿出一个表格
sheet = file.get_sheet_by_name(sheets[0])
#最大行数
#print(sheet.max_row)
#最大列数
#print(sheet.max_column)
#表名
#print(sheet.title)
for lineNum in range(1, sheet.max_row + 1):
#print(lineNum)
lineList = []
#print(sheet.max_row, sheet.max_column)
for columnNum in range(1, sheet.max_column + 1):
#拿数据
value = sheet.cell(row=lineNum, column=columnNum).value
#if value != None:
lineList.append(value)
print(lineList)
#读取一张表的数据
#不能处理xls文件
path = r"C:\Users\xlg\Desktop\Python-1704\day15\5、excel自动化办公\sunck.xlsx"
readXlsxFile(path)
# xlsx xls
# openpyxl -> xlsx
from openpyxl.reader.excel import load_workbook
def readXlsxFile(path):
dic = {}
file = load_workbook(filename=path)
sheets = file.get_sheet_names()
print(len(sheets))
for sheetName in sheets:
sheet = file.get_sheet_by_name(sheetName)
#一张表的所有数据
sheetInfo = []
for lineNum in range(1, sheet.max_row + 1):
lineList = []
for columnNum in range(1, sheet.max_column + 1):
value = sheet.cell(row=lineNum, column=columnNum).value
lineList.append(value)
sheetInfo.append(lineList)
#将一张表的数据存到字典
dic[sheetName] = sheetInfo
return dic
#不能处理xls文件
path = r"C:\Users\xlg\Desktop\Python-1704\day15\5、excel自动化办公\sunck.xlsx"
dic = readXlsxFile(path)
print(dic["安力博发"])
print(len(dic))
#有序字典
from collections import OrderedDict
#读取数据
from pyexcel_xls import get_data
def readXlsAndXlsxFile(path):
dic = OrderedDict()
#抓取数据
xdata = get_data(path)
for sheet in xdata:
dic[sheet] = xdata[sheet]
return dic
path = r"C:\Users\xlg\Desktop\Python-1704\day15\5、excel自动化办公\sunck.xls"
dic = readXlsAndXlsxFile(path)
print(dic)
print(len(dic))
#有序字典
from collections import OrderedDict
#写入数据
from pyexcel_xls import save_data
def makeExcelFile(path, data):
dic = OrderedDict()
for sheetName, sheetValue in data.items():
d = {}
d[sheetName] = sheetValue
dic.update(d)
save_data(path, dic)
path = r"C:\Users\xlg\Desktop\Python-1704\day15\5、excel自动化办公\b.xls"
makeExcelFile(path, {"表1":[[1,2,3],[4,5,6],[7,8,9]],
"表2": [[11, 22, 33], [44, 55, 66], [77, 88, 99]]})
ppt文件
import win32com
import win32com.client
def makePPT(path):
ppt = win32com.client.Dispatch("PowerPoint.Application")
ppt.Visible = True
#增加一个文件
pptFile = ppt.Presentations.Add()
#创建页 参数1为页数(从1开始) 参数2为类型
page1 = pptFile.Slides.Add(1,1)
t1 = page1.Shapes[0].TextFrame.TextRange
t1.Text = "sunck"
t2 = page1.Shapes[1].TextFrame.TextRange
t2.Text = "sunck is a good man"
page2 = pptFile.Slides.Add(2, 1)
t3 = page2.Shapes[0].TextFrame.TextRange
t3.Text = "kaige"
t4 = page2.Shapes[1].TextFrame.TextRange
t4.Text = "kaige is a good man"
page2 = pptFile.Slides.Add(3, 2)
#保存
pptFile.SaveAs(path)
pptFile.Close()
ppt.Quit()
path = r"C:\Users\xlg\Desktop\Python-1704\day15\6、ppt自动化办公\sunck.ppt"
makePPT(path)
播放音乐
import time
import pygame
#pip install pygame
#音乐路径
filePath = r"C:\Users\xlg\Desktop\Python-1704\day15\7、播放音乐\res\0.mp3"
#初始化
pygame.mixer.init()
#加载音乐
track = pygame.mixer.music.load(filePath)
#播放
pygame.mixer.music.play()
#
time.sleep(5)
#停止
pygame.mixer.music.stop()
修改桌面背景图片
#win键+r -> regedit -> HKEY_CURRENT_USER -> Control panel ->Desktop
import win32api
import win32con
import win32gui
def setWallPaper(path):
#打开注册表
reg_key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, "Control Panel\\Desktop",0,win32con.KEY_SET_VALUE)
#2 拉伸 0 居中 6 适应 10填充
win32api.RegSetValueEx(reg_key, "WallpaperStyle", 0, win32con.REG_SZ, "2")
#
#SPIF_SENDWININICHANGE 立即生效
win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, path, win32con.SPIF_SENDWININICHANGE)
setWallPaper(r"C:\Users\xlg\Desktop\Python-1704\day15\8、修改背景图片\res\6.jpg")
键盘模拟
import win32con
import win32api
import time
'''
win32api.keybd_event(91,0,0,0)
time.sleep(0.1)
win32api.keybd_event(91,0,win32con.KEYEVENTF_KEYUP,0)
'''
while True:
win32api.keybd_event(91, 0, 0, 0)
time.sleep(0.1)
win32api.keybd_event(77, 0, 0, 0)
time.sleep(0.1)
win32api.keybd_event(77, 0, win32con.KEYEVENTF_KEYUP, 0)
win32api.keybd_event(91, 0, win32con.KEYEVENTF_KEYUP, 0)
time.sleep(3)
鼠标模拟
import win32con
import win32api
import time
#设置鼠标的位置
win32api.SetCursorPos([30, 40])
time.sleep(0.1)
#鼠标左键按下
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0,0)
#鼠标左键抬起
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0,0)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0,0)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0,0)
网友评论