Python folder names in the directory

前端 未结 8 1156
傲寒
傲寒 2020-12-23 23:15

how can i get the folder names existing in a directory using Python ?

I want to save all the subfolders into a list to work with the names after that but i dont know

8条回答
  •  -上瘾入骨i
    2020-12-23 23:41

    I use os.listdir

    Get all folder names of a directory

    folder_names = []
    for entry_name in os.listdir(MYDIR):
        entry_path = os.path.join(MYDIR, entry_name)
        if os.path.isdir(entry_path):
            folder_names.append(entry_name)
    

    Get all folder paths of a directory

    folder_paths = []
    for entry_name in os.listdir(MYDIR):
        entry_path = os.path.join(MYDIR, entry_name)
        if os.path.isdir(entry_path):
            folder_paths.append(entry_path)
    

    Get all file names of a directory

    file_names = []
    for file_name in os.listdir(MYDIR):
        file_path = os.path.join(MYDIR, file_name)
        if os.path.isfile(file_path):
            file_names.append(file_name)
    

    Get all file paths of a directory

    file_paths = []
    for file_name in os.listdir(MYDIR):
        file_path = os.path.join(MYDIR, file_name)
        if os.path.isfile(file_path):
            file_paths.append(file_path)
    

提交回复
热议问题