【14】檔案讀取並格式化處理

來源:互聯網
上載者:User

標籤:color   div   pytho   遍曆   文本   開啟檔案   技術分享   split   分享   

案例:讀取一個郵箱的文本資訊,並產生新的檔案資訊進行儲存
2018-10-23
BUG心得:在一個檔案中兩次開啟檔案不能as 為同一個名的檔案對象,比如下邊的14 和 36 行 分別要不同的名 file_obj 和file_obj2

 一、把如下的檔案結構下的檔案格式化處理為另一個檔案結構儲存

 

#__author:"吉*佳"#date: 2018/10/23 0023#function:# BUG心得:在一個檔案中兩次開啟檔案不能as 為同一個名的檔案對象,比如下邊的14 和 36 行 分別要不同的名 file_obj 和file_obj2# 讀取一個郵箱的文本資訊,並產生新的檔案資訊進行儲存import osimport collections# 處理普通檔案函數def work(filePath):    resultDir = r‘E:\[AAA](千)全棧學習python\18-10-21\day7\resultDir‘    with open(filePath,‘r‘) as file_obj:        while True:            #讀取到第一行資料 如 #[email protected]            lineInfo = file_obj.readline()            # 設定一個退出while迴圈的標誌            if len(lineInfo) < 5:                break            mailPsw = lineInfo.split(‘----‘)[-1]            mailStr = lineInfo.split(‘----‘)[0]            mailType = mailStr.split(‘@‘)[-1].split(‘.‘)[0]            mailDetail = mailStr.split(‘@‘)[0]            #儲存為新的檔案夾和檔案文本操作            newDirPath  = os.path.join(resultDir,mailType)            # 檢測沒有這個檔案夾的話就建立一個            if not os.path.exists(newDirPath):                os.mkdir(newDirPath)            #建立完類型檔案夾之後把新的檔案資訊儲存進去            newFilePath = os.path.join(newDirPath,mailType+‘.txt‘)            with open(newFilePath,‘a‘) as file_obj2:                file_obj2.write(mailDetail)                file_obj2.write(‘----‘)                file_obj2.write(mailPsw+‘\n‘)def getAllDirIT(path):    queue=collections.deque()    #進隊    queue.append(path)    #迴圈,當隊列為空白,停止迴圈    while len(queue) != 0:        #出隊資料 這裡相當於找到A元素的絕對路徑        dirPath = queue.popleft()        # 找出跟目錄下的所有的子目錄資訊,或者是跟目錄下的檔案資訊        dirList = os.listdir(dirPath)        #遍曆該檔案夾下的其他資訊        for filename in dirList:            #絕對路徑            dirAbsPath = os.path.join(dirPath,filename)            # 判斷:如果是目錄dir入隊操作,如果不是dir列印出即可            if os.path.isdir(dirAbsPath):                print("目錄:"+filename)                queue.append(dirAbsPath)            else:                # 找到普通檔案,進行處理資訊。把這個普通檔案的路徑傳遞過去                work(dirAbsPath)# 函數的調用getAllDirIT(r‘E:\[AAA](千)全棧學習python\18-10-21\day7\newdir‘)

 

結果:

163郵箱處理後儲存的帳號密碼

 

 

 

【14】檔案讀取並格式化處理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.