프로그래밍

[Python] 디렉토리에서 원하는 파일목록 리스트로 가져오기

e_yejun 2020. 7. 18. 02:22

* 현재 디렉토리에서 모든 파일 리스트 반환

# -*-coding:utf-8-*-

import os

filelist_path = []

# 현재 디렉토리 경로
path = os.getcwd()
	
# 리스트로 반환
filelist = os.listdir(path)

 

 

* 하위 디렉토리의 파일 리스트를 반환하고 싶을 경우

# -*-coding:utf-8-*-

import os

filelist_path = []

# 현재 디렉토리 경로
path = os.getcwd()

# 하위 디렉토리 경로 추가 지정
path += '\\low_diectory\\'	
    
# 디렉토리가 없을 경우 예외처리
try:
	filelist = os.listdir(path)
except Exception as ex:
	print('%s -> No Directory : ./low_directory' % ex)
	exit(0)    
    
# 리스트로 반환
filelist = os.listdir(path)

 

 

* 원하는 파일 확장자 지정 (.xlsx)

# -*-coding:utf-8-*-

import os

def file_arr():
	filelist_path = []
	path = os.getcwd()
	
	filelist = os.listdir(path)
	filelist.sort()
	
	for file in filelist:
		if file.find('zNex~$hare') is not -1:
			continue
		if file.find('.xlsx') is not -1:
			filelist_path.append(path + '\\' + file)
			
	return filelist_path
    
   
filelist_path = file_arr()
print(filelist_path)

위의 코드는 .xlsx 파일만으로 엑셀 파일 리스트를 만든다.

이때, zNex_$hare(한컴오피스 임시파일)를 찾아서 continue 해주는 이유는 임시파일은 건너 뛰기 위해서다.

 

최종적으로 filelist_path는 최상위 경로로 부터 파일의 절대경로를 리스트 형태로 가지고 있다.