728x90
반응형

배경

지정 경로 내 폴더 및 파일

  - 위와 같이 지정 경로에 폴더 및 파일이 있는 상태에서, 각 파일/폴더 경로 및 이름 리스트를 얻는 방법

  - 파이썬 표준 라이브러리 os, glob 사용 (어떤 기능을 구현하는 방법은 무수히 많음)

 

방법

Python code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import glob
import os
 
# 경로
path = "D:\\01-PERSONAL\\04-Blog\\*" 
print()
 
# 파일 폴더 모두 출력
Path_List = glob.glob(path)
Name_List = [os.path.basename(x) for x in Path_List]
 
print("Path_List1:", Path_List)
print("Name_List1:", Name_List)
print()
 
# 파일만 출력 (파일에는 ".{확장자}" 가 있다는 점을 활용)
Path_List2 = glob.glob(path + '.*')
Name_List2 = [os.path.basename(x) for x in Path_List2]
 
print("Path_List2:", Path_List2)
print("Name_List2:", Name_List2)
print()
 
# 폴더만 출력 (파일에는 ".{확장자}" 가 있다는 점을 활용)
Path_List3 = [x for x in Path_List if x not in Path_List2]
Name_List3 = [x for x in Name_List if x not in Name_List2]
 
print("Path_List3:", Path_List3)
print("Name_List3:", Name_List3)
print()
 
# 폴더 경로 출력하는 다른 방법
Path_List4 = glob.glob(path + '*\\')
print("Name_List4:", Path_List4)
cs

 

  - glob.glob({File path}) : File path 가 포함된 모든 폴더 및 파일의 경로 return

  - os.path.basename({File path}) : 입력된 경로의 가장 하위 경로만 return

  - Line17 : 파일만을 뽑기위해, '.*' 을 File path에 추가

  - Line25 : Path_List 에서 Path_List2에 있는 원소를 빼서 폴더만을 얻기

  - 주의 : 본 방법은 기본적으로 확장자의 존재 여부를 이용해서 파일 및 폴더를 구분하므로, 확장자가 없는 파일의 경우 폴더로 분류하게 된다. (위 폴더 경로에 DsegFault는 파일이지만 폴더로 분류 됨)

  - Line33 : 폴더는 다음 경로도 존재한다는 점을 이용해서 폴더 경로 얻기

 

Output

Path_List1: ['D:\\01-PERSONAL\\04-Blog\\Blog_NextLine.f90', 'D:\\01-PERSONAL\\04-Blog\\DSegFault', 'D:\\01-PERSONAL\\04-Blog\\DSegFault.f90', 'D:\\01-PERSONAL\\04-Blog\\dsegfault_main.png', 'D:\\01-PERSONAL\\04-Blog\\Folder', 'D:\\01-PERSONAL\\04-Blog\\Folder2', 'D:\\01-PERSONAL\\04-Blog\\~$그림.pptx', 'D:\\01-PERSONAL\\04-Blog\\그림.pptx']
Name_List1: ['Blog_NextLine.f90', 'DSegFault', 'DSegFault.f90', 'dsegfault_main.png', 'Folder', 'Folder2', '~$그림.pptx', '그림.pptx']

Path_List2: ['D:\\01-PERSONAL\\04-Blog\\Blog_NextLine.f90', 'D:\\01-PERSONAL\\04-Blog\\DSegFault.f90', 'D:\\01-PERSONAL\\04-Blog\\dsegfault_main.png', 'D:\\01-PERSONAL\\04-Blog\\~$그림.pptx', 'D:\\01-PERSONAL\\04-Blog\\그림.pptx']
Name_List2: ['Blog_NextLine.f90', 'DSegFault.f90', 'dsegfault_main.png', '~$그림.pptx', '그림.pptx']

Path_List3: ['D:\\01-PERSONAL\\04-Blog\\DSegFault', 'D:\\01-PERSONAL\\04-Blog\\Folder', 'D:\\01-PERSONAL\\04-Blog\\Folder2']
Name_List3: ['DSegFault', 'Folder', 'Folder2']

Name_List4: ['D:\\01-PERSONAL\\04-Blog\\Folder\\', 'D:\\01-PERSONAL\\04-Blog\\Folder2\\']
728x90
반응형

+ Recent posts