os.walk( dir )는 주어진 디렉토리( dir  ) 내의 모든 하위 디렉토리와 파일을 재귀적으로 탐색한다. 

os.listdir()가 주어진 디렉토리 내 정보만 가져오는 것과 대비된다.

 

os.walk 사용법

for (root, dirs, files) in os.walk(path_dir):  # path_dir : 탐색할 루트 폴더
    print("# root : " + root)  # 현재 폴더의 전체 경로

    if len(dirs) > 0:
        for dir_name in dirs:  # '현재' 폴더에 포함된 하위 디렉토리 명단.
            print("dir: " + dir_name)

    if len(files) > 0:  # 디렉토리가 아닌, '현재' 폴더에 포함된 파일 명단.
        for file_name in files:
            print("file: " + file_name)

 

 

반응형

'programming > Python' 카테고리의 다른 글

고유 식별자(unique id) 생성  (0) 2025.04.28
venv 가상환경  (0) 2024.08.21
파이썬 패턴  (0) 2024.06.12
파일, 디렉토리 관리  (0) 2024.06.12
DataFrame, Column name 변경  (0) 2020.09.06

 

자주 쓰는 패턴 모음

기능 패턴
숫자 ^[0-9]*$
영문자 ^[a-zA-Z]*$
한글 ^[가-힣]*$
영어 & 숫자 ^[a-zA-Z0-9]*$
E-Mail ^[a-zA-Z0-9]+@[a-zA-Z0-9]+$
휴대폰 ^01(?:0|1|[6-9]) - (?:\d{3}|\d{4}) - \d{4}$
일반전화 ^\d{2,3} - \d{3,4} - \d{4}$
IP 주소 ([0-9]{1,3}) \. ([0-9]{1,3}) \. ([0-9]{1,3}) \. ([0-9]{1,3})
모든 기호 (공백, 개행 제외) \.|\,|\"|\'|\!|\@|\#|\$|\%|\^|\&|\*|\(|\)|\-|\_|\=|\+|\\|\||\?|\~|\`

 

반응형

'programming > Python' 카테고리의 다른 글

os.walk - 하위 디렉토리 포함 모든 파일 탐색  (0) 2025.04.10
venv 가상환경  (0) 2024.08.21
파일, 디렉토리 관리  (0) 2024.06.12
DataFrame, Column name 변경  (0) 2020.09.06
DataFrame, indexing - loc, iloc  (0) 2020.09.05

주요 함수

getcwd() 현재 작업 디렉터리를 반환 os.getcwd()
mkdir() 지정된 경로에 새로운 디렉터리(폴더)를 생성
e.g.) /test/dir_a/dir_b
os.mkdir(path)
makedirs() 지정된 경로 내에 있는 상위, 하위 디렉토리(폴더)를 모두 생성
exist_ok = True 옵션은 생성할 폴더가 이미 있을 때 exception을 방지함

e.g.) /test/dir_a/dir_b     # →  /test 아래 dir_a와 dir_b가 없다면 전부 생성
os.makedirs(path, exist_ok = True)
exists() 지정된 경로가 존재하는지 확인 (True/False 값 반환) os.path.exists(path)
isdir() 지정된 경로가 디렉터리인지 확인 (True/False 값 반환) os.path.isdir(path)
isfile() 지정된 경로가 파일인지 확인(True/False 값 반환) os.path.isfile(path)
abspath() 지정된 경로의 절대 경로를 반환 os.path.abspath(path)
join() 운영 체제에 맞게 경로를 연결하여 새 경로를 생성 os.path.join(path1, path2)
split() 경로를 디렉터리와 파일로 분리(튜플로 반환) os.path.split()

 

텍스트 파일 오픈

f = open("a.txt", 'r')
lines = f.readlines()
for line in lines:
    print(line)
f.close()

 


 
디렉토리/파일 관리

os.chdir(path) 작업 디렉토리(현재 위치) 변경
os.getcwd() 작업 디렉토리(현재 위치) 정보 확인
os.remove( filename or path ) 파일이나 디렉토리 삭제
os.mkdir( path ) 디렉토리 생성
os.makedirs( path ) 디렉토리 생성 , /root/user/home/local/temp ... 처럼 긴 경로도 한 번에 생성 가능
os.path.abspath(filename) 파일의 상대 경로를 절대 경로로 변경하는 함수
os.path.exists(filename) 파일 존재 여부 확인 함수 (주어진 경로, 이름의 파일이 있는지 조사)
os.curdir() 현재 디렉토리 정보 확인
os.pardir() 부모 디렉토리 정보 확인
os.sep() 디렉토리 분리 문자 확인. windows "\", linux "/" 반환
os.symlink(src, dst) 원본 파일(src)에 대한 심볼릭 링크(dst)를 생성
os.rename(src, dst) 원본 파일명(src)을 주어진 파일명(dst)으로 변경

 

 

파일 목록 관리

glob.glob(wildcard)  패턴을 이용하여 파일 목록 조회
os.listdir(path)  해당 디렉토리(path)의 전체 목록 조회
dircache.listdir(path)  os.listdir(path)와 동일. 단, path가 변경되지 않으면 이미 읽은 정보를 재활용
dircache.annotate(head, list) 일반 파일명과 디렉토리명 구분
os.walk(path) 주어진 디렉토리(path) 내 모든 하위 디렉토리와 파일을 재귀적으로 탐색

 

 
파일명 관리

os.path.basename(filename) 파일명 추출
os.path.dirname(filename) 디렉토리 정보 추출
os.path.split(filename) 경로와 파일명 분리
os.path.splitdrive(filename) 드라이브명과 나머지 분리 (MS windows)
os.path.splitext(filename) 파일명과 확장자 분리

 

 

기타

os.walk

2025.04.10 - [programming/Python] - os.walk - 하위 디렉토리 포함 모든 파일 탐색

 

os.walk - 하위 디렉토리 포함 모든 파일 탐색

os.walk( dir )는 주어진 디렉토리( dir  ) 내의 모든 하위 디렉토리와 파일을 재귀적으로 탐색한다. os.listdir()가 주어진 디렉토리 내 정보만 가져오는 것과 대비된다. os.walk 사용법for (root, dirs, files)

driz2le.tistory.com

 

반응형

'programming > Python' 카테고리의 다른 글

venv 가상환경  (0) 2024.08.21
파이썬 패턴  (0) 2024.06.12
DataFrame, Column name 변경  (0) 2020.09.06
DataFrame, indexing - loc, iloc  (0) 2020.09.05
visdom server port 변경  (0) 2020.03.15

 

□ Jupyter notebook 명령키 일람

 

Command Mode (press Esc to enable) Edit Mode (press Enter to enable)
Enter   enter edit mode Tab   code completion or indent
Shift-Enter   run cell, select below Shift-Tab   tooltip
Ctrl-Enter   run cell Ctrl-]   indent
Alt-Enter   run cell, insert below Ctrl-[   dedent
Y   to code Ctrl-A   select all
M   to markdown Ctrl-Z   undo
R   to raw Ctrl-Shift-Z   redo
1  to heading 1 Ctrl-Y   redo
2  to heading 2 Ctrl-Home   go to cell start
3  to heading 3 Ctrl-Up   go to cell start
4  to heading 4 Ctrl-End   go to cell end
5  to heading 5 Ctrl-Down   go to cell end
6  to heading 6 Ctrl-Left   go one word left
Up   select cell above Ctrl-Right   go one word right
K   select cell above Ctrl-Backspace   delete word before
Down   select cell below Ctrl-Delete   delete word after
J   select cell below Esc   command mode
A   insert cell above Ctrl-M   command mode
B   insert cell below Shift-Enter   run cell, select below
X   cut selected cell Ctrl-Enter   run cell
C   copy selected cell Alt-Enter   run cell, insert below
Shift-V   paste cell above Ctrl-Shift-Subtract   split cell
V   paste cell below Ctrl-Shift--   split cell
Z   undo last cell deletion Ctrl-S   Save and Checkpoint
D,D   delete selected cell Up   move cursor up or previous cell
Shift-M   merge cell below Down   move cursor down or next cell
S   Save and Checkpoint Shift   ignore
Ctrl-S   Save and Checkpoint
L   toggle line numbers
O   toggle output
Shift-O   toggle output scrolling
Esc   close pager
Q   close pager
H   show keyboard shortcut help
I,I   interrupt kernel
0,0   restart kernel
Space   scroll down
Shift-Space   scroll up
Shift   ignore

 

□ 기타 명령 모음

  - ipynb 파일 → py 파일 변환

    콘솔창에서 아래 명령 수행


    jupyter nbconvert --to script [파일명].ipynb



반응형

+ Recent posts