nakka soft world !

[Python] 디렉토리 관련 명령어 본문

프로그래밍언어/Python

[Python] 디렉토리 관련 명령어

nakka 2021. 6. 7. 21:33
728x90

알면 알수록 강력한 기능들이 많은 언어가 Python이 아닌가 싶습니다.

오늘 알려드릴 내용도 일반적인 상황에서 자주 사용되지 않을 수도 있지만,

파일 관련 데이터를 자주 다루시는 분들에게는 자주 사용될 기능에 대해서 알려 드리려 합니다.

파일, 폴더 관련 기능들인데, 차근 차근 확인 해보시죠.

 

해당 Sample Test를 위한 폴더 tree 구조는 아래와 같습니다.

 

1. 폴더 이동하기

우선 특정 폴더로 이동하는 명령어 입니다. 상대 경로 절대 경로 모두 가능합니다.

아래 os.chdir을 전후로 Path가 변경됨을 확인 해볼 수 있습니다.

import os

# 폴더 이동하기
print("========= 폴더 이동하기============")
print(os.getcwd())
os.chdir('./depth2')  # 폴더 이동하기. change directory.
print(os.getcwd())
========= 폴더 이동하기============
/data001/sangyeob.na/Temp/depth1
/data001/sangyeob.na/Temp/depth1/depth2

 

2. 파일 or 폴더 속성 확인하기

전달된 Path가 있는 경로 인지, 파일 path인지 폴더 path인지, 용량은 얼마나 되는지를 확인 하는 명령어 입니다.

import os

# 속성 확인하기
print("========= 속성 확인하기===========")
name1 = "text.txt"
name2 = "dirA"

for name in name1, name2:
    print("filename : ", name)
    print("getsize: ", os.path.getsize(name))   # 크기 구하기
    print("exists : ", os.path.exists(name))    # 존재 하는지 여부 확인
    print("isdir  : ", os.path.isdir(name))     # 폴더인지 여부 확인
    print("isfole : ", os.path.isfile(name))    # 파일인지 여부 확인
    print("==================================")
========= 속성 확인하기===========
filename :  text.txt
getsize:  0
exists :  True
isdir  :  False
isfole :  True
==================================
filename :  dirA
getsize:  4096
exists :  True
isdir  :  True
isfole :  False
==================================

 

3. 절대 경로, 상대 경로 유무 확인

전달된 경로가 상대 경로 인지, 절대 경로 인지 확인하고, 상대 경로를 절대 경로로 변경하는 명령어 입니다.

import os

# 절대 경로, 상대 경로 확인하기
print("========= 절대 경로, 상대 경로 확인하기===========")
path = "/home/workspace/myproject/dirA"
print("isabs   : ", os.path.isabs('.'))       # 상대 경로 인지 확인
print("isabs   : ", os.path.isabs(path))      # 상대 경로 인지 확인
print("abspath : ", os.path.abspath('.'))     # 절대 경로 구하기
print("abspath : ", os.path.abspath('../dirB')) # Path 추가해서 절대 경로 구하기
========= 절대 경로, 상대 경로 확인하기===========
isabs   :  False
isabs   :  True
abspath :  /home/workspace/depth1/depth2
abspath :  /home/workspace/depth1/dirB

 

4. 폴더 이동 경로 확인하기

A폴더에서 B폴더로 이동하는 경로 구하기 입니다. A폴더에서 B폴더로 갈때 어떻게 이동해야 하는가에 대한 답을 알려 줍니다.

import os

# 폴더 이동 Path 확인 하기
print("=========  폴더 이동 Path 확인 하기===========")
os.chdir('./dirA')
file = "/data001/sangyeob.na/Temp/depth1/depth2/dirB"
print(os.path.relpath(file))
=========  폴더 이동 Path 확인 하기===========
../dirB

 

5. Windows / Linux 자동으로 폴더 경로 나누기

이글을 작성하게 된 이유이기도 한데, Linux와 Windows의 폴더 구분자는 /와 \로 서로 다릅니다.

python은 OS구분없이 동작하기에 폴더 경로를 나눌때 OS가 어떤거인지 확인하고, 구분자를 별도로 지정하고 경로를 나눌필요 없이 os.path.sep를 사용하면 자동으로 os에 맞는 구분자를 return합니다.

import os

#자동 구분자로 Path 나누기
print("=========  자동 구분자로 Path 나누기===========")
path_win = "C:\\workspace\\myproject\\dirB"
paht_linux = "/home/workspace/myproject/dirA"

for file in path_win, paht_linux:
    print(file.split(os.path.sep))
=========  자동 구분자로 Path 나누기===========
['C:\\workspace\\myproject\\dirB']
['', 'home', 'workspace', 'myproject', 'dirA']

 

끝~!

728x90
Comments