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 =