一、讀取指定目錄下的全部文件
二、讀取指定文件,輸出文件內容
三、建立一個文件並保存到指定目錄性能
Python寫代碼簡潔高效,實現以上功能僅用了40行左右的代碼~ 昨天用Java寫了一個寫入、建立、複製、重命名文件要將近60行代碼;spa
不過簡潔的代價是犧牲了一點點運行速度,但隨着硬件性能的提高,運行速度的差別會愈來愈小,直到人類沒法察覺~插件
#-*- coding: UTF-8 -*-
''' 一、讀取指定目錄下的全部文件 二、讀取指定文件,輸出文件內容 三、建立一個文件並保存到指定目錄 '''
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 IDE,發現Subline tx2對中文的支持很差, NotePad++ 代碼自定義顏色不方便。code
用來用去仍是Eclipse最順手,裝上PyDev插件以後,編寫Python代碼很方便;blog