이번 포스팅에서는 os 라이브러리를 이용한 경로 및 폴더 관리, shutil 라이브러리를 이용한 파일 복사 방법에 대한 소소한 팁들을 소개하겠습니다. 

os 라이브러리에 대해서 소개해 놓은 페이지 ( https://docs.python.org/3/library/os.html )에 가보면 '기타 운영 체계에 대한 인터페이스 (Miscellaneous operating system interfaces)' 라고 소개를 하면서 스크롤 압박에 굉장히 심할 정도로 여러개의 함수들을 소개해 놓았습니다. 

그 많은 것을 모두 소개하기는 힘들구요, 그중에서도 이번 포스팅에서는 제가 자주 쓰는 함수들만 몇 개 선별해서 소개하도록 하겠습니다. 


  1. os 라이브러리를 이용한 경로 및 폴더 생성, 조회, 변경


먼저 os 라이브러리를 불러오겠습니다. 


import os # Miscellaneous operating system interfaces



1-1. 현재 작업경로 확인하기: os.getcwd()


# os.getcwd(): returns the current working directory

os.getcwd()

'C:\\Users\\admin\\python'

 



1-2. 작업경로 안에 들어있는 파일 리스트 확인하기: os.listdir(path)


# os.listdir(path): return a list of then entries in the directory given by path

os.listdir(os.getcwd()) # a list of files at current directory

['.ipynb_checkpoints', 'numpy_adding_new_axis.ipynb', 'Numpy_clip.ipynb', 'python_os.ipynb'] 




1-3. 작업경로 바꾸기: os.chdir(path)


# os.chdir(path): change the current working directory to path

base_dir = 'C:/Users/admin'

os.chdir(base_dir)

os.getcwd()

 'C:\\Users\\admin'




1-4. 기존 경로와 새로운 폴더 이름을 합쳐서 하위 경로 만들기: os.path.join()


# join one or more path components

path = os.path.join(base_dir, 'os')

path

'C:/Users/admin\\os'




1-5. 새로운 폴더를 만들기: os.mkdir(path)

 

# create a directory named path with numeric mode

os.mkdir(path)




1-6. 경로가 존재하는지 확인하기: os.path.isdir(path)


# return True if path is an existing directory

os.path.isdir(path)

True

 



1-7. 파일이나 경로 이름 바꾸기: os.rename(old_path_name, new_path_name)


# rename the file or directory src to dst

# os.rename(src, dst)

dst_path = os.path.join(base_dir, 'os_renamed')

os.rename(path, dst_path)

os.path.isdir(dst_path) # check whether dst_path is renamed or not

True

 



  2. shutil 라이브러리를 이용한 파일 복사: shutil.copyfile(src, dst)


먼저, 파일을 복사해올 소스 경로(source directory, from)와 파일을 복사해놓은 종착지 경로(destination directory, to)를 만들어보겠습니다. 


# creating src_dir, dst_dir

base_dir = 'C:/Users/admin'

src_dir = os.path.join(base_dir, 'src_dir')

dst_dir = os.path.join(base_dir, 'dst_dir')


os.mkdir(src_dir)

os.mkdir(dst_dir)

 


다음으로, 소스 경로(src_dir)에 'file_1.txt', 'file_2.txt', 'file_3.txt' 라는 이름으로 메모장으로 작성한 간단한 텍스트 파일 3개를 저장해두었습니다. (직접 수작업으로 메모장 열고 문자 몇개 입력하고 저장함)

os.listdir() 를 사용하여 소스 경로(src_dir)에 들어있는 3개의 텍스트파일 이름을 fnames 라는 이름의 리스트로 만들어두었습니다. 


# put file_1, file_2, file_3 into src_dir

fnames = os.listdir(src_dir)

fnames

['file_1.txt', 'file_2.txt', 'file_3.txt'] 



마지막으로, shutil 라이브러리를 불러오고, shutil.copyfile(src, dst) 함수를 사용하여 소스 경로(source directory)에 들어있는 3개의 텍스트 파일을 종착지 경로(destination directory)로 복사해보겠습니다. 

이때 for loop 문을 사용하여 텍스트 파일 별로 shutil.copyfile(src, dst)를 적용해주면 됩니다. 


# copy files from src to dst directory

import shutil


for fname in fnames:

    src = os.path.join(src_dir, fname)

    dst = os.path.join(dst_dir, fname)

    shutil.copyfile(src, dst)


os.listdir(dst_dir)

['file_1.txt', 'file_2.txt', 'file_3.txt'] 




  3. os와 shutil 라이브러리를 이용한 폴더 삭제, 파일 삭제하기


아래와 같이 3개의 텍스트 파일이 들어있는 'C:/Users/admin/os' 라는 경로의 폴더를 예로 들어보겠습니다. 


os.listdir('C:/Users/admin/os')

['big_data.txt', 'my_data.txt', 'sample_data.txt']



3-1. 경로(폴더) 제거하기: os.rmdir(path)

경로(폴더) 안에 파일이 없어야지 os.rmdir()을 사용할 수 있습니다. 경로(폴더) 안에 파일이 있으면 아래처럼 "OSError: [WinError 145] 디렉토리가 비어 있지 않습니다"라는 에러가 발생합니다. 


# OSError: directory is not empty 

os.rmdir('C:/Users/admin/os')

---------------------------------------------------------------------------
OSError                                   Traceback (most recent call last)
<ipython-input-11-4b25f55d427c> in <module>()
----> 1 os.rmdir('C:/Users/admin/os')

OSError: [WinError 145] 디렉터리가 비어 있지 않습니다: 'C:/Users/admin/os'


os.path.isdir(dst_path) # check whether dst_path is removed or not

False

 


3-2. 파일 삭제하기 : os.remove(path)

os.remove() 는 인자로 1개의 파일 경로를 받습니다. 한번에 한개씩 지워야 하므로 불편한점이 있습니다. 


 # delete file

os.remove('C:/Users/admin/os/my_data.txt')

os.remove('C:/Users/admin/os/big_data.txt')

os.remove('C:/Users/admin/os/sample_data.txt')



위에서 'C:/Users/admin/os' 경로 안의 파일 3개를 모두 삭제했으므로 이제 os.rmdir() 을 사용해서 폴더를 삭제할 수 있습니다. 

# delete directory only when it is empty

os.rmdir('C:/Users/admin/os') 


경로(폴더)가 존재하는지 os.path.isdir(path)로 확인해보겠습니다. 방금전에 경로를 os.rmdir()로 삭제를 했기 때문에 False 를 반환하였습니다. 

# check whether the directory is present or not

os.path.isdir('C:/Users/admin/os') 

False


3-3. 경로(폴더)와 파일을 한꺼번에 모두 삭제하기 : shutil.rmtree(path)


os.mkdir('C:/Users/admin/os')


# delete directory and files at once

import shutil

shutil.rmtree('C:/Users/admin/os')

 


많은 도움이 되었기를 바랍니다. 

이번 포스팅이 도움이 되었다면 아래의 '공감~'를 꾹 눌러주세요. :-)

728x90
반응형
Posted by Rfriend
,