首先看一下我我们的邮箱数据文件:
现在我们要实现的功能是按照邮箱类型给上面的邮箱数据分类,并创建邮箱类型.txt
import collections
import os
def work(path):
resPath =r"E:\python\PycharmProjects\python基础学习\day05\res"
# 打开文件
with open(path,"r")as f:
#处理每一行文件
while True:
# dashoidhas@163.com
lineInfo = f.readline()
if len(lineInfo) <5:
break
#邮箱的字符串
mailStr = lineInfo.split("----")[0]
#邮箱类型的目录
# print(mailStr)
fileType = mailStr.split("@")[1].split(".")[0]
# print(mailStr)
dirStr = os.path.join(resPath,fileType)
# print(dirStr)
if not os.path.exists(dirStr):
#不存在
os.mkdir(dirStr)
#创建文件
filePath = os.path.join(dirStr,fileType +".txt")
with open(filePath,"a")as fw:
fw.write(mailStr+"\n")
这里用到了目录遍历的深度遍历,还有广度遍历和递归遍历,他们所要实现的效果是一样的。
def getAllDirBfs(path):
queue = collections.deque()
# 进队
queue.append(path)
while len(queue) !=0:
# 出队数据
dirPath = queue.popleft()
# 找出所有的文件
fileList = os.listdir(dirPath)
for fileNamein fileList:
# 绝对路径
fileAbsPath = os.path.join(dirPath,fileName)
# 判断是否是目录,是目录就进队,不是就打印
if os.path.isdir(fileAbsPath):
print("目录:"+ fileName)
queue.append(fileAbsPath)
else:
# 处理普通文件
work(fileAbsPath)
getAllDirBfs(r"E:\python\PycharmProjects\python基础学习\day05\dir")
运行程序
创建的邮箱类型文件夹 创建的邮箱;类型文本 成功分类
网友评论