[Python] 파일 관리: os module

Jae Gyeong Lee·2023년 2월 7일

os: 폴더 생성 및 이동, 삭제 시 사용

import os

1. 작업 중인 디텍토리 확인

getcwd 함수

  • get current working directory
os.getcwd()

=> 현재 내가 있는 디렉토리 이름이 나옴

2. 특정 디렉토리로 이동

chdir 함수

  • change directory
os.chdir("이동할 디렉토리")

=> 입력한 디렉토리로 이동

3. 특정 디렉토리 내 파일(또는 폴더) 목록 확인

listdir 함수

  • list directory
os.listdir("디렉토리 위치")

=> 입력한 디렉토리 안에 있는 파일(또는 폴더) 목록을 보여줌
=> list 형태로 출력됨

4. 폴더 생성

4.1. mkdir 함수

  • make directory
  • 폴더를 만들어 주는 함수(한번에 하나씩 생성)

dir1 > dir2 > dir3 처럼 계층적으로 만들고자 하면

  • os.mkdir dir1 > os.mkdir dir2 > os.mkdir dir3
os.mkdir('경로/폴더명')
- 설정한 경로에 '폴더명'으로된 폴더 생성

os.mkdir('폴더명')
- 현재 작업중인 위치에 '폴더명'으로된 폴더 생성

4.2. makedirs 함수

  • make directories
  • 폴더를 만들어 주는 함수(하위 폴더 포함, 한번에 전부)
os.makedirs('경로/폴더명1/폴더명2/폴더명3')
- 설정한 경로에 폴더명1 > 폴더명2 > 폴더명3 생성

os.makedirs('/폴더명1/폴더명2/폴더명3')
- 현재 작업중인 위치에 폴더명1 > 폴더명2 > 폴더명3 생성

os.makedirs('경로/폴더명...', exist_ok=True)
-  exist_ok = True 설정한 경로에 폴더명이 존재하더라도 에러 없이 진행

mkdir vs makedirs

  • mkdir: 에러 확인 가능
  • makedirs: 의도하지 않은 문제 발생

5. 폴더 삭제

5.1. rmdir

  • remove directory
  • 폴더를 하나씩 삭제하는 함수(폴더 안에 다른 파일이 없는)

5.2. removedirs

  • remove directories
  • 폴더를 삭제하는 함수(폴더 안에 어떤 파일이 있던 다 지움)

5. os.walk

os.walk('경로')

  • 특정 '경로' 내 <폴더>, <파일>, <하위 폴더 및 내부 파일> 모두 탐색
>>> 디렉토리 구조 예)

C:\test
  ㄴdir1
    ㄴdir1_1
	  ㄴtxt1.txt
	  ㄴtxt2.txt
	ㄴdir1_2
	  ㄴtxt3.txt
	ㄴtxt7.txt
  ㄴdir2
    ㄴtxt4.txt
	ㄴexcel1.xlsx
  ㄴtxt5.txt
  ㄴtxt6.txt
  ㄴtxt7.txt
import os
file_path = r'C:\test'

for file in os.walk(file_path):
    print(file)
>>>
('C:\\test', ['dir1', 'dir2'], ['txt5.txt', 'txt6.txt', 'txt7.txt'])
('C:\\test\\dir1', ['dir1_1', 'dir1_2'], [])
('C:\\test\\dir1\\dir1_1', [], ['txt1.txt', 'txt2.txt'])
('C:\\test\\dir1\\dir1_2', [], ['txt3.txt'])
('C:\\test\\dir2', [], ['excel1.xlsx', 'txt4.txt'])
  • 반환 형태: (path, dir, file)
    path = 탐색한 경로 반환
    dir = 해당 path 내 폴더들을 list로 반환
    file = 해당 path 내 파일들을 list로 반환

6. os.path

os.path.split('경로')

  • '경로'와 '파일명' 분리

os.path.splitext('경로')

  • '경로//파일'과 '파일 확장자명' 분리

https://dotsnlines.tistory.com/514
https://coding-kindergarten.tistory.com/83


7. exists()

  • 인자로 전달한 파일/폴더의 존재 여부를 확인
  • 인자 <= 파일/폴더의 경로
  • 결과로 True 또는 False 반환
import os

if os.path.exists('test.txt')
	print('o')

8. makedirs()

  • 인자로 전달한 값으로 폴더를 생성
  • 인자 <= 폴더명, 생성 폴더의 경로
os.makedirs('hello') # hello 폴더 생성
  • 동일한 명칭으로 이미 파일/폴더가 존재하면 에러.
    - 에러 방지를 위해 옵션을 줌
os.makedirs('hello', exist_ok = True)
  • 에러가 발생하지 않고 그냥 넘어감
os.unlink('test.txt')
  • 인자로 전달한 파일을 삭제할 때 사용
    - 폴더 삭제 불가, 파일만 삭제 가능
  • 인자 <= 삭제할 파일명

10. copyfile()

  • 파일을 복사할 때 사용
  • 인자 <= 원본 파일명, 복사할 파일명
shutil.copyfile('test.txt', 'test2.txt')

11. copytree()

  • '폴더'를 복사할 때 사용
  • 인자 <= 원본 폴더명, 복사할 폴더명
shutil.copytree('hello', 'hello2') #hello 폴더를 hello2 폴더로 복사

복사할 폴더(hello2)가 이미 생성되어 있으면, error

12. rmtree()

  • '폴더'를 삭제할 때 사용
  • 인자 <= 삭제할 폴더
shutil.rmtree('hello2') #hello2 폴더 삭제

13. 파일경로/파일명 분리

$os.path.dirname(full_path)  # 디렉토리 경로만
$os.path.basename(full_path) # 파일명만
# 전체 파일 경로
full_path = 'C:\\Users\\jaegyeong\\Desktop\\Test_directory\\wav_file\\test.wav'

# 경로와 파일명 분리
file_path = os.path.dirname(full_path)   # 디렉토리 경로만 추출
 >>> 'C:\\Users\\jaegyeong\\Desktop\\Test_directory\\wav_file'

file_name = os.path.basename(full_path)       # 파일명만 추출
 >>> 'test.wav'

14. 파일경로/파일명/확장자 분리

$os.path.splitext()
file = 'C:\\Users\\jaegyeong\\Desktop\\Test_directory\\wav_file\\test.wav'

os.path.splitext(file)

 >>> ('C:\\Users\\jaegyeong\\Desktop\\Test_directory\\wav_file\\test', '.wav')

15. 파일경로/파일명 합치기

  • 중간에 파일경로 추가 가능
$os.path.join(file_path, file_name)
full_path = os.path.join(file_path, file_name)
 >>> 'C:\\Users\\jaegyeong\\Desktop\\Test_directory\\wav_file\\test.wav'
full_path = os.path.join(file_path, file_path1, file_path2)
full_path = os.path.join(file_path, file_path1, file_path2, file_name)

16. 특정 디렉토리에 특정 확장자의 파일만 추출

$os.listdir(directory)
def extract_wav(directory):

    all_files = os.listdir(directory) #디렉토리 내 모든 파일(listdir)을 불러옴

    wav_files = [] # .wav 파일만 저장할 빈 리스트 생성
    for file in all_files:
        if file.endswith('.wav'):	# 파일 이름이 .wav로 끝나는지(endswith) 확인
            wav_files.append(file)	# .wav로 끝나는 파일만 리스트에 추가

	# wav_files = [file for file in all_files if file.endswith('.wav')] #comprehension

    return wav_files

17. 특정 디렉토리에 특정 폴더 생성

folder_name = 'new_folder'

if not os.path.exists(folder_name): #해당 디렉토리에 해당 폴더명이 존재하지 않는 경우만
	os.mkdir(folder_name)
profile
안녕하세요 반갑습니다. 공부한 내용들을 기록하고 있습니다.

0개의 댓글