python3自动化获取各种文件内容

一, 获取各种文件内容

1,读写csv文件内容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import csv

def readCsv(path):
infoList =[]
with open(path, "r") as f:
allFileInfo = csv.reader(f)
#print(allFileInfo)
for row in allFileInfo:
infoList.append(row)
return infoList


path = r"D:\py_work\zidonghua\工作簿1.csv"
info = readCsv(path)

for read in info:
print(read)

2,写csv文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import csv


def writeCsv(path,data):
with open(path,"w") as f:
writer =csv.writer(f)
for rowData in data:
writer.writerow(rowData)



path = r"D:\py_work\zidonghua\工作簿2.csv"

writeCsv(path, [[1,2,3],[4,5,6],[7,8,9]])

3,读取PDF文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import sys
import importlib
importlib.reload(sys)

# pip installl pdfminer
#pip install pdfminer3K
#from pdfminer.pdfparser import PDFParser,PDFDocument
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 PDFTextractionNotAllowed
else:
#解析数据
#数据管理器
manager = PDFResourceManager()
#创建一个PDF设备的对象
laparams =LAParams()
device = PDFPageAggregator(manager, laparams=laparams)
#解释器对象
interpreter = PDFPageInterpreter(manager, device)
#开始循环处理,每次处理一页,
#print(pdfFile.get_pages())
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"D:\py_work\zidonghua\test.pdf"
toPath = r"D:\py_work\zidonghua\jenkis.txt"
readPDF(path,toPath)

4,播放音乐

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import time
import pygame

#pip install pygame

#播放音乐的路径、
filePath = r"D:\py_work\zidonghua\陈粒-奇妙能力歌 [mqms2].mp3"
#初始化
pygame.mixer.init()

#加载音乐
track = pygame.mixer_music.load(filePath)

#播放
pygame.mixer.music.play()

time.sleep(60)
#暂停
pygame.mixer.music.pause()


#停止
pygame.mixer.music.stop()

5,修改桌面背景图片

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

#win键 +r -> regedit ->HKEY_CURRENT_USER ->Control Panel ->Desktop-> WallPaper

import win32api
import win32con
import win32gui,sys,time

shuo = "使用前先在桌面创建一个目录名为tu,然后把背景图片放进tu目录去并命名为0.jpg"
print(" ")
print(" ")
print(shuo)
shu = input("准备好了就请输入yes/no,no是退出\n")
if shu == "yes":
print("开始换背景图片")
elif shu == "no" :
print("开始退出脚本")
sys.exit()
else:
print("请正确输入yes或no")
time.sleep(1)
print("本程序退出了")
sys.exit()

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")

#win32api.RegSetValueEx(reg_key, )
#win32api.RegSetValueEx(reg_key,"WallPaper")
#win32con.SPIF_SENDWININICHANGE立即生效
win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER ,path, win32con.SPIF_SENDWININICHANGE)



path = r"C:\Users\Administrator\Desktop\tu\0.jpg"

setWallPaper(path)

6,整蛊小程序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import time
import pygame
import win32api
import win32con
import win32gui,sys
#线程模块
import threading
def go():
pygame.mixer.init()
while True:
for i in range(5):
filePath =r"C:\Users\Administrator\Desktop\tu" +"\\" +str(i) +".mp3"
track =pygame.mixer.music.load(filePath)

pygame.mixer.music.play()
time.sleep(10)
pygame.mixer.music.stop()


#go()
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")

#win32api.RegSetValueEx(reg_key, )
#win32api.RegSetValueEx(reg_key,"WallPaper")
#win32con.SPIF_SENDWININICHANGE立即生效
win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER ,path, win32con.SPIF_SENDWININICHANGE)

#path = r"C:\Users\Administrator\Desktop\tu\0.jpg"

th =threading.Thread(target = go, name="LoopThread")
th.start()


while True:
for i in range(6,10):
filePath = r"C:\Users\Administrator\Desktop\tu" +"\\" + "ding"+ str(i) +".jpg"
print(filePath)
time.sleep(5)
setWallPaper(filePath)

break

#setWallPaper(path)

7,键盘模拟

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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:
#77是D 91win键 左37 上是38 右是39,下是40,
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)

8,鼠标模拟

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import win32con
import win32api
import time

#设置鼠标的位置
win32api.SetCursorPos([20,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)
#相当于双击

9,读取doc与docx文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import win32com
import win32com.client

def readWordFile(path):
#调用系统world功能,可以处理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()
#退出world
mw.Quit()


path =r"D:\py_work\zidonghua\yichen.docx"
readWordFile(path)

10,读取doc与docx文件并写入其他文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import win32com
import win32com.client

def readWordFile(path,toPath):
#调用系统world功能,可以处理doc和docx两种文件
mw = win32com.client.Dispatch("Word.Application")
#打开文件
doc = mw.Documents.Open(path)

for paragraph in doc.Paragraphs:
line = paragraph.Range.Text

#print(line)

#将world的数据保存到另一个文件
doc.SaveAs(toPath, 2) #2表示为txt文件
#关闭文件
doc.Close()
#退出world
mw.Quit()


path =r"D:\py_work\zidonghua\yichen.docx"
toPath = r"D:\py_work\zidonghua\yichen.txt"
readWordFile(path,toPath)

11,创建world文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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.Quit()



names = ["张三","李四","王五"]
for name in names:
path = os.path.join(os.getcwd(),name)


makeWordFile(path,name)

12,读取xlsx文件单个表格

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#xlsx xls
#openpyxl -> xlsx



from openpyxl.reader.excel import load_workbook

def readXlsxFile(path):
#打开文件
file = load_workbook(filename=path)
#所有表格的名称sheet
#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)



path =r"D:\py_work\zidonghua\test1.xlsx"

readXlsxFile(path)

13,读取xlsx文件所有表格

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#xlsx xls
#openpyxl -> xlsx



from openpyxl.reader.excel import load_workbook

def readXlsxFile(path):
dic = {}
#打开文件
file = load_workbook(filename=path)
#所有表格的名称sheet
#print(file.get_sheet_names())
sheets = file.get_sheet_names()
#打印有多少张表sheet
#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
# if value != None:
lineList.append(value)
sheetInfo.append(lineList)


#将一张表的数据存在字典
dic[sheetName] = sheetInfo
return dic




#不能处理xls文件
path =r"D:\py_work\zidonghua\test1.xlsx"

dic = readXlsxFile(path)

#获取所有表的内容
#print(dic)
#print(len(dic))
#获取所有表中的某张表
print(dic["路由器"])
#获某张表中的第几行0行代表每列的名称
print(dic["路由器"][0])
print(dic["路由器"][2])
print(dic["路由器"][3])

14,返回xls和xlsx的数据

这种方式同时支持两种,且代码简单

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#需要安装依赖包
'''
pip install openpyxl
pip install xlrd
pip install future
pip install xlwt-future
pip install pyexcel-io
pip install ordereddict
pip install pyexcel
pip install pyexcel-xls
'''
#导入有序字典模块
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"D:\py_work\zidonghua\test.xls"
dic = readXlsAndXlsxFile(path)
print(dic)
print(len(dic))

#获取所有表中的某张表
#print(dic["路由器"])
#获某张表中的第几行0行代表每列的名称
#print(dic["路由器"][0])
#print(dic["路由器"][2])
#print(dic["路由器"][3])

15,写入xls文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#导入有序字典模块
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"D:\py_work\zidonghua\b.xls"
data = {"表1":[[1,2,3],[4,5,6],[7,8,9]],"表2":[[11,22,33],[44,55,66],[77,88,99]]}

makeExcelFile(path, data)

16, 写ppt

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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 = "yichen"

t2 = page1.Shapes[1].TextFrame.TextRange
t2.Text = "yichen is a good man"

page2 = pptFile.Slides.Add(2, 1)
t3 = page2.Shapes[0].TextFrame.TextRange
t3.Text = "yichen"

t4 = page2.Shapes[1].TextFrame.TextRange
t4.Text = "yichen is a good man"

page3 = pptFile.Slides.Add(3, 2)
t5 = page3.Shapes[0].TextFrame.TextRange
t5.Text = "yichen"

t6 = page3.Shapes[1].TextFrame.TextRange
t6.Text = "yichen is a good man"
#保存
pptFile.SaveAs(path)
pptFile.Close()
ppt.Quit()



path = r"D:\py_work\zidonghua\yichen.ppt"

makePPT(path)

评论


:D 一言句子获取中...

加载中,最新评论有1分钟缓存...