標籤:
1、讀取指定目錄的檔案
2、讀取本地檔案,輸出檔案內容
3、寫入並儲存一個檔案到指定目錄
Python的代碼非常簡潔高效,實現以上三大功能僅用了40行左右的代碼~ 之前用Java讀寫、建立、複製、重新命名檔案要寫50多行代碼,Python的效率的確很高;
#-*- coding: UTF-8 -*- ‘‘‘1、讀取指定目錄的檔案2、讀取本地檔案,輸出檔案內容3、寫入並儲存一個檔案到指定目錄‘‘‘import os# 遍曆指定目錄,顯示目錄下的所有檔案名稱def eachFile(filepath): pathDir = os.listdir(filepath) for allDir in pathDir: child = os.path.join(‘%s%s‘ % (filepath, allDir)) print child.decode(‘gbk‘) # .decode(‘gbk‘)是解決中文顯示亂碼問題# 讀取檔案內容並列印def readFile(filename): fopen = open(filename, ‘r‘) # r 代表read for eachLine in fopen: print "讀取到得內容如下:",eachLine fopen.close() # 輸入多行文字,寫入指定檔案並儲存到指定檔案夾def writeFile(filename): fopen = open(filename, ‘w‘) print "\r請任意輸入多行文字"," ( 輸入 .號斷行符號儲存)" while True: aLine = raw_input() if aLine != ".": fopen.write(‘%s%s‘ % (aLine, os.linesep)) else: print "檔案已儲存!" break fopen.close()if __name__ == ‘__main__‘: filePath = "D:\\FileDemo\\Java\\myJava.txt" filePathI = "D:\\FileDemo\\Python\\pt.py" filePathC = "C:\\" eachFile(filePathC) readFile(filePath) writeFile(filePathI)
Python遍曆檔案夾和讀寫檔案的方法