아이공의 AI 공부 도전기

[Python] 중요한 os 함수 살펴보기

 

 

     

 

공식 python os 설명은 아래에 존재합니다.

자세한 내용을 살펴보고 싶다면 아래 링크를 확인해주세요.

https://docs.python.org/ko/3/library/os.html

 

os — 기타 운영 체제 인터페이스 — Python 3.10.2 문서

os — 기타 운영 체제 인터페이스 소스 코드: Lib/os.py 이 모듈은 운영 체제 종속 기능을 사용하는 이식성 있는 방법을 제공합니다. 파일을 읽거나 쓰고 싶으면 open()을 보세요, 경로를 조작하려면 o

docs.python.org

 

 

os 함수를 소개하는 순서는 개인적으로 많이 사용하는 순서대로 설명하도록 하겠습니다.

 

 

실습에 사용할 Directory과 file 설정

 

우선 os에 대한 설명과 예시를 설명하기에 앞서 미리 구성한 샘플 디렉토리와 파일에 대해 먼저 소개하도록 하겠습니다.

도식화하면 아래와 같습니다.

 

└── sample_dir
     ├── img_dir1
     │      ├──animal
     │      │    └──animal-gb3b672022_640.jpg
     │      ├──bird
     │      │    └──finch-g2171c23e8_640.jpg
     │      ├──human
     │      │    ├──three-g96ddf6974_640.jpg
     │      │    └──vietnam-gfda5da2cc_640.jpg
     │      └──plant
     │           ├──nature-g101f68a2d_640.jpg
     │           └──tree-gdaf460e7d_640.jpg
     ├──img_dir2
     │      ├──building
     │      │    └──york-minster-g87ee4b6f3_640.jpg
     │      ├──glass
     │      │    ├──building-g1a2fd2b23_640.jpg
     │      │    └──stained-glass-g446808813_640.jpg  
     │      └──waterfall
     │           └──waterfall-gf0dc8d755_640.jpg     
     └──img_dir2
            ├──grass
            │    └──tree-g454ac1b81_640.jpg
            ├──ocean
            │    └──waves-gcc099869b_640.jpg  
            └──sky
                 ├──caucasus-g63c1fbf1c_640.jpg
                 └──sunset-gc2d3a4090_640.jpg

가장 top directory는 sample_dir이고 이 아래 3개의 디렉토리가 존재합니다.

img_dir1, img_dir2, img_dir3

각 디렉토리 폴더는 또 다른 폴더가 존재합니다.

그리고 그 안의 디렉토리 폴더에 이미지 파일을 배치해놓았습니다.

 

이 디렉토리와 파일을 기반으로 예시를 적용했을 때 어떻게 나오는지 설명하도록 하겠습니다.

 

 

1. os.path

 

os 모듈을 사용함에 있어 가장 중요한 것은 아마도 경로일 것입니다. 해당 경로에 도달하기 위해서는 어떤 path를 통과해야하는지를 판단하는 것이 모든 데이터를 활용하는 작업에 있어 가장 중요할 것입니다.

 

고로 첫 번재로 배울 것은 os.path입니다.

 

os.path 관련 자세한 내용은 아래 링크를 참조하세요

https://docs.python.org/ko/3/library/os.path.html

 

os.path — 일반적인 경로명 조작 — Python 3.10.2 문서

os.path — 일반적인 경로명 조작 소스 코드: Lib/posixpath.py (POSIX의 경우) 및 Lib/ntpath.py (윈도우 NT의 경우) 이 모듈은 경로명에 유용한 함수를 구현합니다. 파일을 읽거나 쓰려면 open()을 참조하고, 파

docs.python.org

 

1-1) os.path.join()

 

os.path.join은 특정 폴더와 폴더 혹은 파일 사이의 경로를 이어주는 역할을 합니다. 

이때의 경로는 대부분 상대 경로명으로 나타냅니다.

물론 절대경로 또한 가능합니다.

그러나 일반적으로는 상대 경로

# sample_dir\img_dir1
a = os.path.join('sample_dir','img_dir1')
print(a)

# sample_dir\img_dir1\animal
a = os.path.join('sample_dir','img_dir1','animal')
print(a)

# sample_dir\img_dir1
a = 'sample_dir\\img_dir1'
print(a)

# window에서 활용하는 경로 분리 '/'
# sample_dir/img_dir1/animal
a = 'sample_dir'+'/img_dir1'+'/animal'
print(a)

 

1-2) os.path.isdir() / os.path.isfile() / os.path.exists()

 

os.path.isdir()는 문구에서 느껴지듯 해당 path에 directory가 존재하는지를 묻는 bool 함수입니다.

os.path.isfile() 역시 문구에서 느껴지듯 해당 path에 file이 존재하는지를 묻는 bool 함수입니다.

위 두 방법은 폴더만 혹은 파일만이 존재하는지를 판별하는 것이었다면 os.path.exist()는 해당 파일이나 폴더가 존재하는지를 묻는 bool 함수입니다.

 

a = os.path.isdir('sample_dir')
# True
print(a)
a = os.path.isdir(os.path.join('sample_dir','img_dir1'))
# True
print(a)
a = os.path.isdir(os.path.join('sample_dir','img_dir1','animal'))
# True
print(a)
a = os.path.isdir(os.path.join('sample_dir','img_dir1','bee'))
# False
print(a)

a = os.path.isfile('sample_dir')
# False
print(a)
a = os.path.isfile(os.path.join('sample_dir','img_dir1'))
# False
print(a)
a = os.path.isfile(os.path.join('sample_dir','img_dir1','animal'))
# False
print(a)
a = os.path.isfile(os.path.join('sample_dir','img_dir1','bee'))
# False
print(a)
a = os.path.isfile(os.path.join('sample_dir','img_dir1','animal','animal-gb3b672022_640.jpg'))
# True
print(a)

a = os.path.exists('sample_dir')
# True
print(a)
a = os.path.exists(os.path.join('sample_dir','img_dir1'))
# True
print(a)
a = os.path.exists(os.path.join('sample_dir','img_dir1','animal'))
# True
print(a)
a = os.path.exists(os.path.join('sample_dir','img_dir1','bee'))
# False
print(a)
a = os.path.exists(os.path.join('sample_dir','img_dir1','animal','animal-gb3b672022_640.jpg'))
# True
print(a)
a = os.path.exists(os.path.join('sample_dir','img_dir1','animal','fake_animal.jpg'))
# False
print(a)

 

1-3) os.path.basename()

 

os.path.basename()은 경로 path의 기본 이름을 반환합니다.

이때 directory 또는 file을 가리지 않습니다.

마지막에 위치한 디렉토리나 파일을 반환하는 것을 아래 예시에서 확인할 수 있습니다.

 

# path = 'sample_dir/img_dir1/animal/animal-gb3b672022_640.jpg'
path = os.path.join('sample_dir','img_dir1','animal','animal-gb3b672022_640.jpg')
a = os.path.basename(path)
# animal-gb3b672022_640.jpg
print(a)


# path = 'sample_dir/img_dir1/animal'
path = os.path.join('sample_dir','img_dir1','animal')
a = os.path.basename(path)
# animal
print(a)

 

1-4) os.path.split() / os.path.splitext()

 

os.path.split()는 path 경로명을 (head, tail)로 분할해줍니다. 다만 path가 '/'로 끝나면 tail은 비어있습니다.

첫 번재와 두 번째 사례를 유의깊게 살펴보세요

 

os.path.splitext()는 파일에 해당하는 부분의 확장자를 분리시켜주는 역할을 합니다.

파일이름을 따오기 위해 많이 사용하므로 기억해두세요.

마지막 용례를 잘 살펴보세요.

 

path = 'sample_dir/img_dir1/animal/'
a = os.path.split(path)
# ('sample_dir/img_dir1/animal', '')
print(a)
a = os.path.splitext(path)
# ('sample_dir/img_dir1/animal/', '')
print(a)

path = 'sample_dir/img_dir1/animal'
a = os.path.split(path)
# ('sample_dir/img_dir1', 'animal')
print(a)
a = os.path.splitext(path)
# ('sample_dir/img_dir1/animal/', '')
print(a)

path = os.path.join('sample_dir','img_dir1','animal','animal-gb3b672022_640.jpg')
a = os.path.split(path)
# ('sample_dir\\img_dir1\\animal', 'animal-gb3b672022_640.jpg')
print(a)
a = os.path.splitext(path)
# ('sample_dir\\img_dir1\\animal\\animal-gb3b672022_640', '.jpg')
print(a)

path = os.path.join('sample_dir','img_dir1','animal','animal-gb3b672022_640.jpg')
a = os.path.splitext(os.path.basename(path))
# ('animal-gb3b672022_640', '.jpg')
print(a)
# 'animal-gb3b672022_640
print(a[0])
# '.jpg'
print(a[1])

 

2. os.makedir() / os.makedirs()

 

os.makedir() / os.makedirs() 모두 글자에서 느껴지듯 디렉토리를 생성하는 함수들입니다.

다만, os.makedir()는 단일 폴더를 생성할 뿐이고 이미 폴더가 존재할 경우 에러가 발생합니다.

 

이를 방지하고 더 범용적으로 사용하는 os.makedirs는 제가 좋아하는 함수 중 하나입니다.

경로에 적힌 폴더를 생성하는데 유용하며 존재하지 않는 상위 폴더 또한 자동으로 생성해줍니다.

또한, exist_ok=True로 설정하면 이미 폴더가 생성되어도 에러가 발생하지 않습니다.

 

path = os.path.join('sample_dir','makedir_sameple_dir','dir_sample_test1')

# directory is created in 'sample_dir/makedir_sameple_dir/dir_sample_test1' path
os.makedirs(path, exist_ok=True)

  

3. os.rmdir() / os.remove() 

 

os.rmdir()은 디렉토리 path를 제거합니다.

os.remove()는 파일을 삭제하기 위해 사용합니다. 

 

path = os.path.join('sample_dir','makedir_sameple_dir','dir_sample_test1')

# directory is created in 'sample_dir/makedir_sameple_dir/dir_sample_test1' path
os.makedirs(path, exist_ok=True)

# directory is removed
os.rmdir(path)

path = os.path.join('sample_dir','img_dir1','animal','animal-gb3b672022_640.jpg')
# file is deleted/removed
os.remove(path)

 

4. os.walk()

 

os.walk()는 상위 루트부터 최하위 루트까지 전부를 살펴보며 3튜플을 생성해내는 함수입니다.

(dirpath, dirnames, filenames) = (디렉토리 경로, 디렉토리 이름, 파일이름)

 

이 함수는 특정 경로에 있는 내용을 모두 살피기 때문에 데이터를 다룰 때 매우 유용하기 때문에 제가 좋아하고 많이 사용합니다.

 

for문을 통해 결과들을 도출하며 그 내용을 잘 조합하면 전체 경로를 구성할 수도 있습니다.

 

자세한 내용은 예시를 보면 바로 이해가 됩니다.

 

for dirpath, dirnames, files in os.walk('sample_dir'):
    print(dirpath, dirnames, files)
    
"""
sample_dir ['img_dir1', 'img_dir2', 'img_dir3', 'makedir_sameple_dir'] []
sample_dir\img_dir1 ['animal', 'bird', 'human', 'plant'] []
sample_dir\img_dir1\animal [] ['animal-gb3b672022_640.jpg']
sample_dir\img_dir1\bird [] ['finch-g2171c23e8_640.jpg']
sample_dir\img_dir1\human [] ['three-g96ddf6974_640.jpg', 'vietnam-gfda5da2cc_640.jpg']
sample_dir\img_dir1\plant [] ['nature-g101f68a2d_640.jpg', 'tree-gdaf460e7d_640.jpg']
sample_dir\img_dir2 ['building', 'glass', 'waterfall'] []
sample_dir\img_dir2\building [] ['york-minster-g87ee4b6f3_640.jpg']
sample_dir\img_dir2\glass [] ['building-g1a2fd2b23_640.jpg', 'stained-glass-g446808813_640.jpg']
sample_dir\img_dir2\waterfall [] ['waterfall-gf0dc8d755_640.jpg']
sample_dir\img_dir3 ['grass', 'ocean', 'sky'] []
sample_dir\img_dir3\grass [] ['tree-g454ac1b81_640.jpg']
sample_dir\img_dir3\ocean [] ['waves-gcc099869b_640.jpg']
sample_dir\img_dir3\sky [] ['caucasus-g63c1fbf1c_640.jpg', 'sunset-gc2d3a4090_640.jpg']
"""

  

5. os.rename(path1, path2)

 

os.rename(path1, path2)은 path1의 경로로부터 path2와 같이 파일명을 변경할 때 사용합니다.

이때 변경은 디렉토리 뿐 아니라 파일도 이름 변경이 가능합니다.

 

# directory name is changed from 'dir_sample_test1' to 'rename_dir'
path1 = os.path.join('sample_dir','makedir_sameple_dir','dir_sample_test1')
path2 = os.path.join('sample_dir','makedir_sameple_dir','rename_dir')
os.rename(path1, path2)

# image file name is changed from 'animal-gb3b672022_640.jpg' to 'cat.jpg'
path1 = os.path.join('sample_dir','img_dir1','animal','animal-gb3b672022_640.jpg')
path2 = os.path.join('sample_dir','img_dir1','animal','cat.jpg')
os.rename(path1, path2)

 

6. os.getcwd()

 

os.getcwd()는 현재 경로에 대한 절대 경로 정보를 보여줍니다.

 

# C:\Users\Username\Desktop\test
print(os.getcwd())

 

7. os.listdir()

 

os..listdir()은 현재 디렉토리의 파일 목록 확인할 수 있습니다.

디렉토리 뿐 아니라 파일 또한 확인 가능합니다.

 

# ['img_dir1', 'img_dir2', 'img_dir3']
print(os.listdir('sample_dir'))

# ['animal', 'bird', 'human', 'plant']
print(os.listdir(os.path.join('sample_dir', 'img_dir1')))

# ['animal-gb3b672022_640.jpg']
print(os.listdir(os.path.join('sample_dir', 'img_dir1', 'animal')))

 

Reference

 

1. os 공식 document

 

https://docs.python.org/ko/3/library/os.html

 

os — 기타 운영 체제 인터페이스 — Python 3.10.2 문서

os — 기타 운영 체제 인터페이스 소스 코드: Lib/os.py 이 모듈은 운영 체제 종속 기능을 사용하는 이식성 있는 방법을 제공합니다. 파일을 읽거나 쓰고 싶으면 open()을 보세요, 경로를 조작하려면 o

docs.python.org

 

2. os.path 공식 document

 

https://docs.python.org/ko/3/library/os.path.html

 

os.path — 일반적인 경로명 조작 — Python 3.10.2 문서

os.path — 일반적인 경로명 조작 소스 코드: Lib/posixpath.py (POSIX의 경우) 및 Lib/ntpath.py (윈도우 NT의 경우) 이 모듈은 경로명에 유용한 함수를 구현합니다. 파일을 읽거나 쓰려면 open()을 참조하고, 파

docs.python.org

 

 

 

 

0000 

공유하기

facebook twitter kakaoTalk kakaostory naver band
loading