1. 程式人生 > >python遍歷檔案及子檔案

python遍歷檔案及子檔案

#coding:utf-8   #是用來指定檔案編碼為utf-8的
import os
import codecs#涉及到檔案目錄有中文日文英文,其ASCII格式不一樣
#import tkinter #GUI程式,匯入Tkinter模板  <3.0的python
from tkinter import *   #>3.0的python 寫法
 
def GetAllFiles(path):
 allfile=[]
 for dirpath,dirnames,filenames in os.walk(path):
  for dir in dirnames:
   allfile.append(os.path.join(dirpath,dir))
  for name in filenames:
   allfile.append(os.path.join(dirpath, name))
 return allfile


"""此處 涉及到檔案開啟關閉重複動作
def StoryFilesToTxt(path,string):
    f = codecs.open(path,'a','utf-8')
    f.write(string + '\n')
"""
"""從Frame 派生一個Application類,這是所有Widget的父容器


"""
class Application(Frame):
    def __init__(self,master = None):
        Frame.__init__(self,master)
        self.pack()
        self.createWidgets()
    def createWidgers(self):
        self.helloLabel = Label(self, text = 'hello world!')
        self.helloLabel.pack()
        self.quiteButton = Button(self,text = 'Quit',command = self.quit)
        self.quiteButton.pack()


        


if __name__ == '__main__':
 #path =r"檔案路徑"
 cpath = os.getcwd()  #獲取當前路徑
 #print(cpath)
 path = cpath + '\\資料夾'
 #print(path)
 #path1= r'檔案路徑\StoryFilesToTxt.txt'
 cpath1 = os.getcwd()
 #print(cpath1)
 path1 = cpath1 + '\\StoryFilesToTxt.txt'
 #print(path1)
 
 allfile=GetAllFiles(path)
 f = codecs.open(path1,'a','utf-8')   #解決路徑含有中文日文ASCII不一樣,寫入失敗
 for file in allfile:
   print (file)   ##release時需要將該行註釋掉
   f.write(file + '\n')
 f.close()


  #StoryFilesToTxt(path1,file)