用os模組進行檔案和目錄操作的例項,讀者可以根據需要將每個選項對應的功能獨立 出來在自己的程式中模仿。
阿新 • • 發佈:2018-12-09
#主程式設計了7個使用者選項,使用者選擇不同的選項可以輸出當前路徑下的檔案、改變路徑、
#統計路徑下的檔案數目和總的檔案大小以及查詢指定檔案等操作。
import os,os.path
QUIT='7'
COMMANDS=('1','2','3','4','5','6','7')
MENU="""
1 List the current directory
2 Move up
3 Move down
4 Number of files in the directory
5 Size of the directory in bytes
6 Search for a file name
7 Quit the program
"""
def main():
while True:
print (os.getcwd()) #列印當前工作路徑
print(MENU)
command=acceptCommand() #接收命令輸入的函式
runCommand(command)
if command == QUIT:
print('Have a nice day!')
break
def acceptCommand():
"""接收命令輸入,返回合法命令編號。"""
while True:
command=input("Enter a number :")
if not command in COMMANDS:
print ("Error:command not recognized")
else:
return command
def runCommand(command):
"""執行個編號的命令"""
if command=='1':
listCurrentDir(os.getcwd()) #顯示當前工作路徑
elif command=='2':
moveUp() #到工作目錄的上級目錄
elif command=='3':
moveDown(os.getcwd()) #到工作目錄的下級指定目錄
elif command=='4': #統計當前目錄下的檔案數目
print("The total number of file is",countFiles(os.getcwd()))
elif command=='5': #統計當前目錄下的檔案的位元組數
print("The total number of bytes is",countBytes(os.getcwd()))
elif command=='6': #在當前路徑及目錄下查詢檔案
target=input("Enter the search string:")
fileList=findFlies(target,os.getcwd())
if not fileList:
print ("String not found")
else:
for f in fileList:
print (f)
def listCurrentDir(dirName):
"""列印當前路徑下的檔名"""
lyst=os.listdir(dirName)
for element in lyst:
print (element)
def moveUp():
"""到上一級目錄。"""
os.chdir(".")
def moveDown(currentDir):
"""到下一級指定目錄"""
newDir=input ("Enter the directory name :")
if os.path.exists(currentDir+os.sep+newDir)and os.path.isdir(newDir):
os.chdir(newDir)
else:
print("Error :no such name")
def countFiles(path):
"""統計當前路徑和自目錄下的所含的檔案數目。"""
count=0
lyst=os.listdir(path)
for element in lyst:
if os.path.isfile(element):
count=count+1
else :
os.chdir(element)
count=count+countFiles(oss.getcwd())
os.chdir("..")
return count
def countBytes(path):
"""返回當前路徑和自目錄下的檔案總位元組數"""
count=0
lyst=os.listdir(path)
for element in lyst:
if os.path.isfile(element):
count+=countBytes(os.getcwd())
os.chdir("..")
return count
def findFiles(target,path):
"""在當前路徑及自目錄下查詢制定檔案"""
files=[]
lyst=os.listdir(path)
for element in lyst:
if os.path.isfile(element):
if target in element:
files.append(path+os.sep+element)
else:
os.chdir(element)
files.extend(findFiles(target,os.getcwd()))
os.chdir("..")
return files
main()