有时候我们从网上下载某些.txt文件,想对文件内容进行提取并生成新的目录文件
首先我们应遍历某特定目录下的所有.txt文件
这里我们采用广度遍历目录的方式(队列遍历)
import os
import collections
def getAllDirQue(path):
#创建队列
queue = collections.deque()
#进队
queue.append(path)
while len(queue) != 0:
#出队
dirPath = queue.popleft()
#生成该目录下的所有文件,以列表的形式
filesList = os.listdir(dirPath)
for filesName in filesList:
#绝对路径
fileAbsPath = os.path.join(dirPath,filesName)
if os.path.isdir(fileAbsPath):
#如果是目录就进队,继续遍历
queue.append(fileAbsPath)
else:
#如果是文件就对文件进行操作
work(fileAbsPath)
getAllDirQue(r"C:\Users\admin\project1\day_10\newdir")
通过队列的进队和出队,遍历特定目录下的所有文件,如果是文件就进行work操作
def work(path):
resPath = r"C:\Users\admin\project1\day_10\res"
with open(path,"r") as f:
while True:
#读取一行
fileInfo = f.readline()
if len(fileInfo)<5:
break
#tianshizhu22@163.com----2571519
#邮箱的字符串
mailSrt = fileInfo.split("----")[0]
fileType = mailSrt.split("@")[1].split(".")[0]
mailPath = os.path.join(resPath,fileType)
if not os.path.exists(mailPath):
#不存在,创建
os.mkdir(mailPath)
filePath = os.path.join(mailPath,fileType+"txt")
with open(filePath,"a")as f2:
f2.write(fileInfo)
resPath保存的是存放新生成文件的路径,通过split函数截取我们要的内容,并生成新的文件,如将邮箱163和qq区分开,并分别生成新的文件保存它们,并将内容写进去。这样我们就实现了从某文件中提取信息并生成新文件并保存的过程。