python讀取目錄下所有檔案
阿新 • • 發佈:2019-02-10
#-*- 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)