os: 폴더 생성 및 이동, 삭제 시 사용
import os
getcwd 함수
os.getcwd()
=> 현재 내가 있는 디렉토리 이름이 나옴
chdir 함수
os.chdir("이동할 디렉토리")
=> 입력한 디렉토리로 이동
listdir 함수
os.listdir("디렉토리 위치")
=> 입력한 디렉토리 안에 있는 파일(또는 폴더) 목록을 보여줌
=> list 형태로 출력됨
4.1. mkdir 함수
dir1 > dir2 > dir3 처럼 계층적으로 만들고자 하면
os.mkdir('경로/폴더명')
- 설정한 경로에 '폴더명'으로된 폴더 생성
os.mkdir('폴더명')
- 현재 작업중인 위치에 '폴더명'으로된 폴더 생성
4.2. makedirs 함수
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.1. rmdir
5.2. removedirs
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'])
os.path.split('경로')
os.path.splitext('경로')
https://dotsnlines.tistory.com/514
https://coding-kindergarten.tistory.com/83
import os
if os.path.exists('test.txt')
print('o')
os.makedirs('hello') # hello 폴더 생성
os.makedirs('hello', exist_ok = True)
os.unlink('test.txt')
shutil.copyfile('test.txt', 'test2.txt')
shutil.copytree('hello', 'hello2') #hello 폴더를 hello2 폴더로 복사
복사할 폴더(hello2)가 이미 생성되어 있으면, error
shutil.rmtree('hello2') #hello2 폴더 삭제
$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'
$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')
$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)
$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
folder_name = 'new_folder'
if not os.path.exists(folder_name): #해당 디렉토리에 해당 폴더명이 존재하지 않는 경우만
os.mkdir(folder_name)