python处理文件(完成文件分类)
lower() 函数可以把字符串中所有的字母全部转换成小写。
本示例中,就将两个示例字符串转换成了小写并使用print输出结果。
sampleStr1 = "NATE".lower()
sampleStr2 = "Drake".lower()
print(sampleStr1)
print(sampleStr2)
我们现在把它应用到获取文件后缀名的代码中,将文件后缀名全部转换为小写。
转换之后,再使用之前的代码进行判断,“心动.MP3”就能被正确分类了。
# 使用import导入os模块
import os
# 将阿文的下载文件夹路径 /Users/yequ/Downloads 赋值给变量downloadPath
downloadPath = "/Users/yequ/Downloads"
# 使用os.listdir()函数获取该路径下所有的文件(夹),并赋值给变量allItems
allItems = os.listdir(downloadPath)
# 使用for循环遍历所有文件(夹)
for item in allItems:
# 获取文件后缀名并使用lower()函数转换成小写
extension = os.path.splitext(item)[1].lower()
if extension in [".jpg", ".jpeg", ".gif", ".png", ".bmp"]:
print(f"{item} 图片文件")
elif extension in [".avi", ".mp4", ".wmv", ".mov", ".flv"]:
print(f"{item} 视频文件")
elif extension in [".wav", ".mp3", ".mid", ".ape", ".flac"]:
print(f"{item} 音频文件")
elif extension in [".pdf"]:
print(f"{item} PDF文件")
elif extension in [".docx", ".doc"]:
print(f"{item} Word文件")
elif extension in [".xlsx", ".xls"]:
print(f"{item} Excel文件")
elif extension in [".pptx", ".ppt"]:
print(f"{item} PPT文件")
else:
print(f"{item} 其他文件")
完成了文件分类后,要想办法把文件移动到对应的文件夹中。
在移动文件之前,我们首先需要确认文件的移动路径。
例如,要把某个文件移动到音频文件,就需要确定移动到哪里的音频文件夹中。
例如,图片文件夹的路径为:
/Users/yequ/Downloads/图片文件
使用 os.path.join() 函数来拼接每个分类文件夹的路径。
该函数需要传入两个参数,将两个参数拼接起来组成目标路径。
例如:需要将某个文件夹保存到电脑的桌面上,文件的名称是音频文件。
桌面的路径为: /Users/Desktop
文件夹名字为:"音频文件"
使用 os.path.join() 就能拼接成文件夹的路径。
# 使用import导入os模块
import os
# 将文件路径 "/Users/yequ/Downloads" 赋值给downloadPath
downloadPath = "/Users/yequ/Downloads"
# TODO 使用os.path.join()函数合并downloadPath和"其他文件"并赋值给变量targetPath
targetPath = os.path.join(downloadPath, "其他文件")
# TODO 使用print输出变量targetPath
print(targetPath)
每个文件需要移动的目标文件夹,那么在移动前还需要确定目标文件夹是否存在。
如果目标文件夹不存在,需要先创建文件夹再移动。
例如:心动.mp3 需要移动到音频文件夹中,那么需要先检查 Downloads 文件夹中是否已经创建了音频文件夹。
得到了目标文件夹的路径后,我们可以使用 os.path.exists() 函数来判断该文件夹是否已经存在。
os.path.exists() 函数接受一个路径字符串作为参数,当该路径的文件夹存在时,返回True,不存在时,则返回False。
# 使用import导入os模块
import os
# 班级文件夹名称列表
stuClass = ["一班", "二班", "三班", "四班", "五班", "六班", "七班", "八班", "九班", "十班"]
# 文件夹路径 "/Users/deng"
path = "/Users/deng"
# for循环遍历班级列表
for item in stuClass:
# 使用os.path.join()拼接班级列表,赋值给targetPath
targetPath = os.path.join(path, item)
# 使用os.path.exists()函数判断当目标文件夹不存在时
if not os.path.exists(targetPath):
# 使用格式化输出,x班
print(f"{item}")
我们知道 if 语句用于判断当前条件的真假,只有满足条件时才会执行if语句中的内容。
我们要输出结果为 False 的班级,这里就需要使用关键字 not 运算符 搭配 os.path.exists() 函数,再使用 if语句 来判断结果并输出。
for item in stuClass:
# 使用os.path.join()拼接班级列表,赋值给targetPath
targetPath = os.path.join(path, item)
# TODO 使用os.path.exists()函数判断当目标文件夹不存在时
if not os.path.exists(targetPath):
# TODO 使用格式化输出,x班
print(f"{item}")