본문으로 바로가기

경로 합치기 os.path.join(path1, path2, ...)

경로와 경로를 합치며 Windows(\), Linux(/) 에 모두 호환되므로, 경로를 합칠 때는 join() 을 쓰는 것을 추천합니다.

path = os.getcwd()
print(path)
for file in os.listdir():
    print(file)
dir_name = 'test_dir'
path2 = os.path.join(path, dir_name)
print(path2)
더보기
C:\Users\Desktop\Reference\Example\ex_os
ex1.py
ex2.py
test_dir
C:\Users\Desktop\Reference\Example\ex_os\test_dir

 

디렉터리 확인 os.path.isdir(path) / 파일 확인 os.path.isfile(path)

isdir(), isfile() 은 해당 경로가 디렉터리인지 혹은 파일인지 True/False 를 반환합니다. 

path = os.getcwd()
for file in os.listdir():
    p = os.path.join(path, file)
    if os.path.isdir(p): 
    # if not os.path.isfile(p)
        rst = 'dir'
    else:
        rst = 'file'
    print(f'{p} is {rst}')
더보기
C:\Users\Desktop\Reference\Example\ex_os\ex1.py is file
C:\Users\Desktop\Reference\Example\ex_os\ex2.py is file
C:\Users\Desktop\Reference\Example\ex_os\test_dir is dir

 

다음과 같이 존재하지 않은 경로는 False를 반환.

for file in os.listdir():
    print(file)
path = os.getcwd()
dir_name = 'test_dir2'
path2 = os.path.join(path, dir_name)
print(path2)
print(os.path.isdir(path2))
더보기
ex1.py
ex2.py
test_dir
C:\Users\Desktop\Reference\Example\ex_os\test_dir2
False

 

경로 존재 유무 확인 os.path.exists(path)

해당 경로의 존재 유무를 True/False 로 반환합니다. 

path = os.getcwd()
for file in os.listdir():
    p = os.path.join(path, file)
    print(p, end=' ')
    if os.path.exists(p): 
        print('is exists', end='')
    print()
더보기
C:\Users\Desktop\Reference\Example\ex_os\ex1.py is exists
C:\Users\Desktop\Reference\Example\ex_os\ex2.py is exists
C:\Users\Desktop\Reference\Example\ex_os\test_dir is exists

 

응용) 커맨드라인 구현 -3

 

파이썬 OS 모듈 사용하기 - 현재 경로, 경로 변경, 디렉터리 검색

현재 경로 getcwd() / 경로 변경 chdir() import os path = os.getcwd() print(path) os.chdir('test_dir') path = os.getcwd() print(path) 더보기 C:\Users\Desktop\Reference\Example\ex_os C:\Users\Desktop\R..

jvvp.tistory.com

 

지난 포스트의 마지막 코드를 가지고 왔습니다.

예외 처리를 하지 않았기 때문에 다음과 같은 에러 발생.

cmd = {
    'pwd': os.getcwd,
    'cd': os.chdir,
    'ls': os.listdir,
}
while True:
    ip = input('>> ')
    if ip == 'quit':
        break
    splt = ip.split(' ')
    if splt[0] not in cmd.keys():
        print('- pwd\n- cd [dir]\n- ls')
        continue

    if splt[0] == 'pwd':
        print(cmd[splt[0]]())
    elif splt[0] == 'cd':
        cmd['cd'](splt[1])
    elif splt[0] == 'ls':
        file_list = cmd['ls']()
        for file in file_list:
            print(file)
더보기
>> ls
ex1.py
ex2.py
test_dir
>> cd test_dir2
Traceback (most recent call last):
  File "c:/Users/Desktop/Reference/Example/ex_os/ex2.py", line 57, in <module>
    cmd['cd'](splt[1])
FileNotFoundError: [WinError 2] 지정된 파일을 찾을 수 없습니다: 'test_dir2'

 

exist(), isdir() 을 이용하여 다음과 같이 업데이트 했습니다.

#2 경로 변화, #3 은 파일타입 확인만 합니다.

결과에 cd c:\ 까지 먹히는 것을 확인할 수 있습니다. 

cmd = {
    'pwd': os.getcwd,
    'cd': os.chdir,
    'ls': os.listdir,
}
path = os.getcwd() #1
while True:
    ip = input('>> ')
    if ip == 'quit':
        break
    elif ip == '':
        continue

    splt = ip.split(' ')
    if splt[0] not in cmd.keys():
        print('- pwd\n- cd [dir]\n- ls')
        continue

    if splt[0] == 'pwd':
        print(cmd[splt[0]]())
    elif splt[0] == 'cd':
        dir_name = splt[1]
        path = os.path.join(path, dir_name) #2
        if os.path.exists(path):
            if os.path.isdir(path):
                cmd['cd'](dir_name)
            else:
                print(f'[*] Error, {splt[1]} is file.')
        else:
            print(f'[*] Error, Invalid path : {p}')
    elif splt[0] == 'ls':
        file_list = cmd['ls']()
        for file in file_list:
            p = os.path.join(path, file) #3
            if os.path.isdir(p):
                rst = '[Dir]'
            else:
                rst = '[File]'
            print(f'{rst}\t{file}')
더보기
>> 
>> ls
[File]  ex1.py
[File]  ex2.py
[Dir]   test_dir
>>
>> cd ex1.py
[*] Error, ex1.py is file.
>>
>> cd test_dir2
[*] Error, Invalid path : C:\Users\Desktop\Reference\Example\ex_os\test_dir2
>>
>> cd test_dir
>> 
>> ls
[File]  1.txt
[File]  2.txt
>>
>> cd c:\
>> ls
[Dir]   $Recycle.Bin
[Dir]   Bitnami
[File]  bootTel.dat
[Dir]   Config.Msi
[Dir]   Documents and Settings
[Dir]   grakn
[File]  hiberfil.sys
[Dir]   mecab
[Dir]   MSOCache
[File]  pagefile.sys
[Dir]   PerfLogs
[Dir]   Program Files
[Dir]   Program Files (x86)
[Dir]   ProgramData
[Dir]   Recovery
[Dir]   SMYSoft
[Dir]   src
[File]  swapfile.sys
[Dir]   System Volume Information
[Dir]   Temp
[Dir]   Users
[Dir]   Windows