zoukankan      html  css  js  c++  java
  • python操作目录和文件

    1. 判断目录是否存在 'isdir',删除目录时只有该目录为空才可以 'rmdir'

    import os
    if(os.path.isdir('D:/Python_workspace/spyder_space/test_各种功能/哈哈哈哈')):  #判断目录是否存在
        print('yes')
        os.rmdir('D:/Python_workspace/spyder_space/test_各种功能/哈哈哈哈') #删除目录,只有该目录为空才可以
    else:
        print('no')

    2. 列出目录下的文件/目录名:'listdir'

    #列出目录下的文件名,包括目录名
    file_list=os.listdir('D:/Python_workspace/spyder_space/test_各种功能')
    print(file_list)

    3. 新建目录:'mkdir'

    # 新建目录
    os.mkdir('D:/Python_workspace/spyder_space/test_各种功能/哈哈哈哈')

    4. 判断目录或文件是否存在:Path包

    from pathlib import Path
    file_path = Path(r'D:/Python_workspace/spyder_space/test_各种功能/test_目录.py')
    # file_path = Path(r'D:/Python_workspace/spyder_space/test_各种功能/哈哈哈哈.py')
    if file_path.exists():  #判断文件或目录是否存在
        print('yes')
    else:
        print('no')
        
    # 仅仅判断文件
    from pathlib import Path
    file_path = Path(r'D:/Python_workspace/spyder_space/test_各种功能/test_目录.py')
    # file_path = Path(r'D:/Python_workspace/spyder_space/test_各种功能/哈哈哈哈.py')
    if file_path.is_file():  #判断文件或目录是否存在
        print('yes')
    else:
        print('no')
    
    # 仅仅判断目录
    from pathlib import Path
    file_path = Path(r'D:/Python_workspace/spyder_space/test_各种功能/test_目录.py')
    # file_path = Path(r'D:/Python_workspace/spyder_space/test_各种功能/哈哈哈哈.py')
    if file_path.is_dir():  #判断文件或目录是否存在
        print('yes')
    else:
        print('no')

     5. 直接删除该文件夹(不管是否有子文件,可以本身不为空)—— shutil 包

    import shutil
    if(os.path.isdir('D:/Python_workspace/spyder_space/test_各种功能/哈哈哈哈')):
        shutil.rmtree(r"D:Python_workspacespyder_space	est_各种功能哈哈哈哈")

    6. 依次删除文件夹的子文件和子目录,但是保留该文件夹(也就是执行之后,该文件夹为空)—— os.walk

    # 遍历一个文件夹并删除它的所有子文件夹以及文件
    import os
    for root, dirs, files in os.walk(r"D:Python_workspacespyder_space	est_各种功能哈哈哈哈", topdown=False):
        for file in files:
            os.remove(os.path.join(root, file))  #删文件
        for dir_ in dirs:
            os.rmdir(os.path.join(root, dir_)) # 删目录
    
    #    root 是当前正在遍历的这个文件夹地址
    #    dirs 该文件夹中所有的目录的名字(不包括子目录)
    #    files 该文件夹中所有的文件(不包括子目录)
    #    topdown --可选,为 True,则优先遍历 top 目录,否则优先遍历 top 的子目录(默认为开启)。如果 topdown 参数为 True,walk 会遍历top文件夹,与top 文件夹中每一个子目录。

    参考:

    https://blog.csdn.net/u011961856/article/details/77840374

    https://www.runoob.com/w3cnote/python-check-whether-a-file-exists.html

    https://www.runoob.com/python/os-walk.html

    https://blog.csdn.net/kaida1234/article/details/89553115

  • 相关阅读:
    “介绍一下自己吧”——记2020BUAA软工团队介绍和采访
    [no code][scrum meeting] Alpha 7
    [no code][scrum meeting] Alpha 6
    [no code][scrum meeting] Alpha 5
    [no code][scrum meeting] Alpha 4
    [no code][scrum meeting] Alpha 3
    [no code][scrum meeting] Alpha 2
    [no code][scrum meeting] Alpha 1
    [no_code]团队贡献分分配规则
    [no_code]团队任务拆解Alpha
  • 原文地址:https://www.cnblogs.com/qi-yuan-008/p/11938851.html
Copyright © 2011-2022 走看看