Day1-Python自动化办公-文件自动化处理(DataWhale)

1. 文件自动化处理

1.1 读写文件

1.1.1 文件与文件路径

路径

指明文件在计算机上的位置

文件名

指该位置的文件的名称

os.path.join()函数创建文件名称字符串

import os
os.path.join('Datawhale', 'docu')

> 'Datawhale\\docu' #其中一个斜杠是转义

1.1.2 当前工作目录

os.getcwd() 获取当前工作路径

os.chdir() 改变当前工作目录

1.1.3 路径操作

绝对路径

总是从根文件夹开始

相对路径

相对于程序的当前工作目录,单个".“表示当前目录的缩写,两个”…"表示父文件夹

在这里插入图片描述

os.path.abspath(path) 将相对路径转换为绝对路径,返回参数的绝对路径的字符串

os.path.isabs(path) 判断是否是绝对路径

os.path.relpath(path, start) 返回start路径到path的相对路径的字符串。没有提供start就使用当前工作目录作为开始路径

os.path.dirname(path) 返回当前路径的目录名称

os.path.basename(path) 返回当前路径的文件名称

os.path.split() 同时获得一个路径的目录名称和基本名称

path.split(os.path.sep) 按照文件夹分割斜杠进行分割

os.path.exists(path) 可以检查文件或文件夹是否存在

os.path.isfile(path) 检查文件是否存在

os.path.isdir(path) 检查文件夹是否存在

os.path.abspath('.') #当前路径转化为绝对路径

os.path.isabs('.') 
> False

os.path.isabs(os.path.abspath('.'))
> True

os.path.relpath('D:\\ZZ_Downloads\\B6_OfficeAutomation\\task_test','D:\\')
> 'ZZ_Downloads\\B6_OfficeAutomation\\task_test'

path = 'D:\\ZZ_Downloads\\B6_OfficeAutomation\\task_test\\Excel.png'
os.path.dirname(path)
> 'D:\\ZZ_Downloads\\B6_OfficeAutomation\\task_test'

os.path.basename(path)
> 'Excel.png'

os.path.split(path)
> ('D:\\ZZ_Downloads\\B6_OfficeAutomation\\task_test', 'Excel.png')

(os.path.dirname(path), os.path.basename(path))
> 
('D:\\ZZ_Downloads\\B6_OfficeAutomation\\task_test', 'Excel.png')

path.split(os.path.sep)
> ['D:', 'ZZ_Downloads', 'B6_OfficeAutomation', 'task_test', 'Excel.png']

1.1.4 文件及文件夹操作

  • 创建文件夹os.makedirs()

    若文件夹已存在,不会覆盖会报错

os.makedirs('D:\\ZZ_Downloads\\B6_OfficeAutomation\\task_test\\test1')
  • 查看文件大小os.path.getsize(path)
os.path.getsize('D:\\ZZ_Downloads\\B6_OfficeAutomation\\task_test\\test1\\ZJL.jpg')
  • 查看文件夹内容os.listdir(path)
os.listdir('D:\\ZZ_Downloads\\B6_OfficeAutomation\\task_test\\test1')

查看目录下所有文件的总字节数

totalsize = 0
for filename in os.listdir('D:\\ZZ_Downloads\\B6_OfficeAutomation\\task_test\\test1'):
    totalsize = totalsize + os.path.getsize(os.path.join('D:\\ZZ_Downloads\\B6_OfficeAutomation\\task_test\\test1', filename))
print(totalsize)

1.1.5 文件读写过程

  • 创建文件

    open与close配合使用

full_path = 'D:\\ZZ_Downloads\\B6_OfficeAutomation\\task_test\\test1\\hello1.txt'
file = open(full_path,'w')
file.close()
  • 写入文件

    ‘w’:写入模式,覆盖原有文件,从头开始;

    ‘a’:添加模式,在已有文件的末尾添加文本

file1 = open(full_path, 'w')
file1.write('Hello World!\n') #write需要在字符串末尾添加换行符
file1.close() #关闭后,才能完成写入
  • 读取文件

    read() :读取文件内容

    readlines():按行读取文件中的内容,取得一个字符串列表,列表中每个字符串是文本中的一行且以\n结束

file1 = open(full_path)
content = file1.read()
content
> 'Hello World!\n'

file1 = open(full_path)
content = file1.readlines()
content
> ['Hello World!\n']

1.1.6 保存变量

  1. shelve模块

shelve模块可以将python变量保存到二进制的shelf文件中

在当前工作目录下会生成3个新文件:mydata.bak、mydata.dat、mydata.dir

import shelve
shelfFile = shelve.open('D:\\ZZ_Downloads\\B6_OfficeAutomation\\task_test\\test1\\mydata')
cats = ['Zonphie', 'Pooka', 'Simon']
shelfFile['cats'] = cats
shelfFile.close()

shelf值不必用读模式或写模式打开,直接打开,既可以读也可以写

shelfFile = shelve.open('D:\\ZZ_Downloads\\B6_OfficeAutomation\\task_test\\test1\\mydata')
type(shelfFile)
> shelve.DbfilenameShelf

shelfFile['cats']
> ['Zonphie', 'Pooka', 'Simon']

shelf值有keys()values()方法

shelfFile = shelve.open('D:\\ZZ_Downloads\\B6_OfficeAutomation\\task_test\\test1\\mydata')
list(shelfFile.keys())
> ['cats']

list(shelfFile.values())
> [['Zonphie', 'Pooka', 'Simon']]

shelfFile.close()
  1. pprint.pformat()函数保存变量

返回要打印的内容的文本字符串,这个字符串既易于阅读,也是语法上正确的python代码。

假如,有一个字典,保存在一个变量中,希望保存这个变量和它的内容,以便将来使用。pprint.pformat()函数将提供一个字符串,我们可以将它写入.py文件。这个文件可以成为我们自己的模块,如果需要使用存储其中的变量,就可以导入它。

import  pprint
cats = [{'name':'Zophie','desc':'chubby'},{'name':'Pooka','desc':'fluffy'}]
pprint.pformat(cats)
fileObj = open('D:\\ZZ_Downloads\\B6_OfficeAutomation\\task_test\\test1\\myCats.py', 'w')
fileObj.write('cats=' +pprint.pformat(cats) +'\n')
fileObj.close()

import语句导入模块

import myCats
myCats.cats
> [{'desc': 'chubby', 'name': 'Zophie'}, {'desc': 'fluffy', 'name': 'Pooka'}]

myCats.cats[0]
> {'desc': 'chubby', 'name': 'Zophie'}

myCats.cats[0]['name']
> 'Zophie'

1.1.7 练习

1、如果已有的文件以写模式打开,会发生什么?

已有的文件以写模式打开会报不可读的错误,此时是可写的

practice = open('D:\\ZZ_Downloads\\B6_OfficeAutomation\\task_test\\test1\\hello1.txt','w')
practice.read()

> UnsupportedOperation: not readable

practice.write('Hello\n')
> 6

practice.close()

如果想要读,直接打开即可

practice = open('D:\\ZZ_Downloads\\B6_OfficeAutomation\\task_test\\test1\\hello1.txt')
practice.read()
> 'Hello\n'

practice.close()

2、read()readlines()方法之间的区别

read()直接读取文件内容;readlines() 将文本中的一行(以\n结束)作为一个字符串存成一个列表

practice = open('D:\\ZZ_Downloads\\B6_OfficeAutomation\\task_test\\test1\\hello1.txt')
practice.read()
> 'name\nHello!\nname!\n'

practice.close()
practice = open('D:\\ZZ_Downloads\\B6_OfficeAutomation\\task_test\\test1\\hello1.txt')
practice.readlines()
> ['name\n', 'Hello!\n', 'name!\n']

practice.close()

1.1.8 综合练习

进行美国各州各府的一个小测试,生成随机的测验试卷文件:

  • 创建35份不同的测试卷子;
  • 每份卷子创建50个多重选择题,次序随机;
  • 为每个问题提供一个正确的答案和3个随机的错误答案,次序随机;
  • 将测试试卷写道35个文本文件中
  • 将答案写到35个文本文件中

代码需要满足:

  • 将州和首府保存在一个字典中
  • 针对测试文本文件和答案文本文件,调用open()、write()和close()
  • 利用random.shuffle()随机调整问题和多重选项的次序

1.2 组织文件

1.2.1 文件和文件夹的复制

  1. shutil.copy(source, destination) :将路径source处的文件复制到路径destination处的文件夹,并返回新复制文件绝对路径字符串

destination可以是:

  • 文件名称:将source文件复制为新名称的destination
  • 文件夹:将source文件复制到destination中。若文件夹存在则复制到destination中,若文件夹不存在,则自动生成该文件夹
import shutil
# 将Excel.png文件复制到test1文件夹内
shutil.copy('D:\\ZZ_Downloads\\B6_OfficeAutomation\\task_test\\Excel.png', 'D:\\ZZ_Downloads\\B6_OfficeAutomation\\task_test\\test1')

# 将Excel.png文件复制为新名称test.png文件
shutil.copy('D:\\ZZ_Downloads\\B6_OfficeAutomation\\task_test\\Excel.png', 'D:\\ZZ_Downloads\\B6_OfficeAutomation\\task_test\\test1\\test.png')
  1. shutil.copytree(source, destination) 将路径soure处的文件夹,包括其包含的文件夹和文件,复制到路径destination处的文件夹,并返回新复制文件夹绝对路径字符串。【destination处的文件夹如果存在则会报错】
shutil.copytree('D:\\ZZ_Downloads\\B6_OfficeAutomation\\task_test\\test1','D:\\ZZ_Downloads\\B6_OfficeAutomation\\task_test\\test2')

1.2.2 文件和文件夹的移动与改名

shutil.move(source, destination) :将路径source处的文件/文件夹移动到destination,并返回新位置的绝对路径的字符串

  • 若source和destination是文件夹,且destination存在,则会将source文件夹下所有内容复制到destination文件夹中
  • 若source和destination是文件夹,且destination不存在,则会创建新的文件夹,并复制source中所有的内容
  • 若source和destination是文件,怎source处的文移动到destination中
shutil.move('D:\\ZZ_Downloads\\B6_OfficeAutomation\\task_test\\test1','D:\\ZZ_Downloads\\B6_OfficeAutomation\\task_test\\test2')

1.2.3 文件和文件夹的永久删除

os.unlink(path):删除path处的文件

os.rmdir(path):删除path处的文件夹。该文件夹必须为空,不好含任何文件和文件夹

shutil.rmtree(path):删除path处的文件夹,包含的所有文件和文件夹都会被删除,不可恢复,存在一定的风险。

【注意:一般在第一次运行时,注释掉这些程序,并加上print()函数帮助查看是否是想要删除的文件】

# 先指定操作的文件夹,并查看
os.chdir('D:\\ZZ_Downloads\\B6_OfficeAutomation\\task_test\\test3')
os.getcwd()

for filename in os.listdir():
    if filename.endswith('.dir'):
        #os.unlink(filename)
        print(filename)

send2trash模块,可以将文件或文件夹发送到回收站,而不是永久删除

import send2trash
os.getcwd()
send2trash.send2trash('Excel.png')

1.2.4 遍历目录树

os.walk(path):传入一个文件夹的路径,在for循环语句中使用os.walk()函数,和range()函数遍历一个范围的数字类似,不同的是os.walk()在循环的每次迭代中,返回三个值:

  • 当前文件夹名称的字符串
  • 当前文件夹中子文件夹的字符串列表
  • 当前文件夹中文件的字符串的列表

【当前文件夹指for循环当前迭代的文件夹。程序的当前工作目录,不会因为os.walk()而改变】

for folderName, subFolders, fileNames in os.walk('D:\\ZZ_Downloads\\B6_OfficeAutomation\\task_test'):
    print('The current folder is '+ folderName)
    for subFolder in subFolders:
        print('Subfolder of ' + folderName +':'+ subFolder)
    for filename in fileNames:
        print('File Inside '+ folderName + ':'+ filename)
    print('')

1.2.5 zipfile模块压缩文件

1.创建和添加zip文件

zipfile.ZipFile('filename.zip','w'):以写模式创建一个压缩文件

write('filename', 'compress_type=zipfile.ZIP_DEFLATED')

  • 传入的是路径,将压缩该路径所指的文件,将它添加到zip文件中
  • 传入的是字符串,代表要添加的文件名。
  • compress_type:压缩类型,可以默认为zipfile.ZIP_DEFLATED

【写模式会擦除zip文件中所有原有的内容。只希望将文件添加到原有的zip文件中,需要向zipfile.ZipFile()传入’a’作为第二参数,以添加模式打开zip文件】

os.chdir('D:\\ZZ_Downloads\\B6_OfficeAutomation\\task_test\\test3')
import zipfile
# 将同一文件夹下的文件压缩
newzip = zipfile.ZipFile('new.zip','w')
newzip.write('hello1.txt', compress_type=zipfile.ZIP_DEFLATED)
newzip.close()
# 不同文件夹下的文件压缩
newzip = zipfile.ZipFile('new.zip','w')
newzip.write('D:\\ZZ_Downloads\\B6_OfficeAutomation\\task_test\\test3\\newtest\\text1.txt', compress_type=zipfile.ZIP_DEFLATED)
newzip.close()
# 创建一个example1.zip压缩文件,将test3文件夹下所有文件进行压缩
newzip = zipfile.ZipFile('example1.zip','w')
for folderName, subFolders, fileNames in os.walk('D:\\ZZ_Downloads\\B6_OfficeAutomation\\task_test\\test3'):
    for filename in fileNames:
        newzip.write(os.path.join(folderName,filename), compress_type=zipfile.ZIP_DEFLATED)
newzip.close()        

2.读取zip文件

zipfile.ZipFile(filename)

  • namelist():返回zip文件中包含的所有文件和文件夹的字符串列表
  • getinfo():返回一个特定文件的ZipInfo对象
    • file_size:文件大小
    • compress_size:压缩后文件大小
examplezip = zipfile.ZipFile('example1.zip')
examplezip.namelist()

testInfo = examplezip.getinfo('ZZ_Downloads/B6_OfficeAutomation/task_test/test3/tt.jpg') #文件名称需要与namelist保存一致
testInfo.file_size
testInfo.compress_size

3.从zip文件中解压缩

extractall():从zip文件中解压缩所有文件和文件夹,放到当前工作目录。也可以传递一个文件夹名称。

extract():从zip文件中解压单个文件。也可以传递一个文件夹名称。返回值是被压缩后文件的绝对路径。

examplezip = zipfile.ZipFile('example1.zip')
examplezip.extractall('.\zip')
examplezip.close()
examplezip = zipfile.ZipFile('example1.zip')
examplezip.extract('ZZ_Downloads/B6_OfficeAutomation/task_test/test3/tt.jpg')
>'D:\\ZZ_Downloads\\B6_OfficeAutomation\\task_test\\test3\\ZZ_Downloads\\B6_OfficeAutomation\\task_test\\test3\\tt.jpg'
examplezip.close()

1.2.6 练习

  1. 编写一个程序,遍历一个目录树,查找特定扩展名的文件(.pdf或.jpg)。将他们拷贝到一个新的文件夹
import os 
import shutil

for folderName, subFolders, fileNames in os.walk('D:\\ZZ_Downloads\\B6_OfficeAutomation\\task_test\\test1'):
    for filename in fileNames:
        if filename.endswith('.jpg'):
            shutil.copy(folderName+"\\"+filename,'D:\\ZZ_Downloads\\B6_OfficeAutomation\\task_test\\new')
 # 注意:文件夹不能存放在test1下面
  1. 编写一个程序,遍历一个目录树,查找特别大的文件或文件夹。将文件的绝对路径打印到屏幕上

思路:先判断文件的大小,文件大于26000字节的输出,并且认为该文件所在的文件夹也需要输出,之后针对文件小于26000字节的向上找文件夹继续判断,然后输出文件夹,逐级向上直到最后输出所有的特别大的文件和文件夹

import os 
import shutil

totalsize = 0
for folderName, subFolders, fileNames in os.walk('D:\\ZZ_Downloads\\B6_OfficeAutomation\\task_test\\test1'):
    for filename in fileNames:
        if os.path.getsize(folderName+'\\'+filename)>26000:
            print(folderName+'\\'+filename)
            foldername1 = folderName
        else:
            for subfolder in subFolders:
                totalsize = totalsize+os.path.getsize(folderName+'\\'+filename)
                if totalsize > 26000:
                    print(folderName+'\\'+subfolder)
    print(foldername1)  
  1. 编写一个程序,在一个文件夹中,找到所有带指定前缀的文件,例如:spam001.txt,spam002.txt,并定位缺失的编号(例如存在spam001.txt和spam003.txt,但不存在spam002.txt),让该程序在所有后面的文件改名,消除缺失的编号。再编写另一个程序,在一些连续编号的文件中,空出一些编号,以便加入新的文件。

2. 自动发送电子邮件

smtplib:负责发送邮件

email:负责构造邮件格式和内容

邮件发送需要遵守SMTP协议,python内置对SMTP的支持,可以发送纯文本邮件、HTML邮件以及带附件的邮件

# 1.导入相关模块
import smtplib
from smtplib import SMTP_SSL #加密邮件内容,防止中途被拦截
from email.mime.text import MIMEText #构造邮件正文
from email.mime.image import MIMEImage #构造邮件图片
from email.mime.multipart import MIMEMultipart #将邮件的各个部分装在一起,邮件的主体
from email.header import Header #邮件的文件头,标题,接收人
# 2.设置邮箱域名、发件人邮箱、邮箱授权码、收件人邮箱
host_server = 'smtp.163.com' #sina邮箱smtp服务器

sender_163 = 'xxxxx@163.com' #发件人邮箱

pwd = 'xxxxx' #pwd为邮箱的授权码

receiver = 'xxxxx@163.com'
# 3.构建MIMEMultipart对象代表邮件本身,可以添加文本、图片、附件等
msg = MIMEMultipart()  #邮件主体
# 4. 设置邮件头部内容
mail_title = 'python自动化办公'  #邮件标题
msg["Subject"] = Header(mail_title, 'utf-8') #装入主体
msg['From'] = sender_163  #发件人
msg['To'] = Header('测试邮件','utf-8') #标题
# 5. 添加正文文本
mail_content = 'Hello, 这是测试邮件!' #邮件正文

message_text = MIMEText(mail_content, 'plain', 'utf-8')
#构造文本,参数1:正文内容;参数2:文本格式;参数3:编码方式

msg.attach(message_text) 
#向MIMEMultipart对象添加文本对象
# 6. 添加图片
image_data = open('D:\\ZZ_Downloads\\B6_OfficeAutomation\\task_test\\test1\\ZJL.jpg','rb')
#二进制读取照片
message_image = MIMEImage(image_data.read()) #设置读取获取的二进制数据
image_data.close() #关闭打开的文件
msg.attach(message_image) #添加图片文件到邮件信息中
# 7. 添加附件(excel表格)
atta = MIMEText(open('D:\\ZZ_Downloads\\B6_OfficeAutomation\\task_test\\test1\\text.xlsx','rb').read(), 'base64','utf-8') #构造附件
atta['Content-Disposition'] = 'attachment; filename="name"' #设置附件信息
msg.attach(atta) #添加附件到邮件信息
# 8. 发送邮件
smtp = SMTP_SSL(host_server)  #SSL登录,创建SMTP对象
smtp.login(sender_163, pwd) #登录邮箱,参数1:邮箱地址;参数2:邮箱授权码
smtp.sendmail(sender_163, receiver, msg.as_string())
# 发送邮件,参数1:发件人邮箱地址;参数2:接收人邮箱地址;参数3:将邮件内容格式改为str
print('邮件发送成功')
smtp.quit

> 邮件发送成功
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值