用os模块进行文件和目录操作的实例,读者可以根据需要将每个选项对应的功能独立 出来在自己的程序中模仿。

#主程序设计了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()



猜你喜欢

转载自blog.csdn.net/qq_38970783/article/details/84837512