首先看一下我我們的郵箱數(shù)據(jù)文件:
現(xiàn)在我們要實現(xiàn)的功能是按照郵箱類型給上面的郵箱數(shù)據(jù)分類袱蜡,并創(chuàng)建郵箱類型.txt
import collections
import os
def work(path):
resPath =r"E:\python\PycharmProjects\python基礎(chǔ)學(xué)習(xí)\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)
#創(chuàng)建文件
? ? ? ? ? ? filePath = os.path.join(dirStr,fileType +".txt")
with open(filePath,"a")as fw:
fw.write(mailStr+"\n")
這里用到了目錄遍歷的深度遍歷材诽,還有廣度遍歷和遞歸遍歷,他們所要實現(xiàn)的效果是一樣的寿烟。
def getAllDirBfs(path):
queue = collections.deque()
# 進(jìn)隊
? ? queue.append(path)
while len(queue) !=0:
# 出隊數(shù)據(jù)
? ? ? ? dirPath = queue.popleft()
# 找出所有的文件
? ? ? ? fileList = os.listdir(dirPath)
for fileNamein fileList:
# 絕對路徑
? ? ? ? ? ? fileAbsPath =? os.path.join(dirPath,fileName)
# 判斷是否是目錄,是目錄就進(jìn)隊辛燥,不是就打印
? ? ? ? ? ? if os.path.isdir(fileAbsPath):
print("目錄:"+ fileName)
queue.append(fileAbsPath)
else:
# 處理普通文件
? ? ? ? ? ? ? ? work(fileAbsPath)
getAllDirBfs(r"E:\python\PycharmProjects\python基礎(chǔ)學(xué)習(xí)\day05\dir")
運行程序