본문으로 바로가기

파일 삭제 os.remove()

파일을 삭제할 때는 os.remove() 를 사용합니다.

os.splitext() 를 이용하여 특정 확장자의 파일을 삭제할 수 있습니다.

import os

print('-'*70)
file_list = os.listdir(dir_path)
print(*file_list)
print('-'*70)
for file in file_list:
    name, ext = os.path.splitext(file)
    if ext == '.jpg':
        file_path = os.path.join(dir_path, file)
        print(file_path)
        os.remove(file_path)
print('='*70)
file_list = os.listdir(dir_path)
print(*file_list)
print('='*70)
더보기
----------------------------------------------------------------------
1.txt 2.txt 3.txt 4.txt girl.jpg girl2.jpg girl3.jpg test2_dir
----------------------------------------------------------------------
c:\Users\Desktop\ex_os\test_dir\girl.jpg
c:\Users\Desktop\ex_os\test_dir\girl2.jpg
c:\Users\Desktop\ex_os\test_dir\girl3.jpg
======================================================================
1.txt 2.txt 3.txt 4.txt test2_dir
======================================================================

 

디렉터리 삭제 os.rmdir()

디렉터리를 삭제할 때는 os.rmdir() 을 사용하고, 비어있지 않을 경우는 다음과 같은 에러가 발생합니다.

import os

print('-'*70)
file_list = os.listdir(dir_path)
print(*file_list)
print('-'*70)
for file in file_list:
    file_path = os.path.join(dir_path, file)
    if os.path.isdir(file_path):
        print(file_path)
        os.rmdir(file_path)
print('='*70)
file_list = os.listdir(dir_path)
print(*file_list)
print('='*70)
더보기
1.txt 2.txt 3.txt 4.txt test2_dir
----------------------------------------------------------------------
c:\Users\Desktop\ex_os\test_dir\test2_dir
Traceback (most recent call last):
  File "c:/Users/Desktop/ex_os/ex4.py", line 31, in <module>
    os.rmdir(file_path)
OSError: [WinError 145] 디렉터리가 비어 있지 않습니다: 'c:\\Users\\Desktop\\ex_os\\test_dir\\test2_dir'

먼저 디렉터리 안의 파일을 삭제하고 디렉터리를 삭제합니다.

import os

print('-'*70)
file_list = os.listdir(dir_path)
print(*file_list)
print('-'*70)
for file in file_list:
    file_path = os.path.join(dir_path, file)
    if os.path.isdir(file_path):
        dir_path2 = file_path
        file_list2 = os.listdir(dir_path2)
        for i, file2 in enumerate(file_list2):
            file_path2 = os.path.join(dir_path2, file2)
            print(f'[{i}] Delete file : {file_path2}')
            os.remove(file_path2)
        os.rmdir(file_path)
print('='*70)
file_list = os.listdir(dir_path)
print(*file_list)
print('='*70)
더보기
----------------------------------------------------------------------
1.txt 2.txt 3.txt 4.txt test2_dir
----------------------------------------------------------------------
[0] Delete file : c:\Users\Desktop\ex_os\test_dir\test2_dir\a.txt
[1] Delete file : c:\Users\Desktop\ex_os\test_dir\test2_dir\b.txt
[2] Delete file : c:\Users\Desktop\ex_os\test_dir\test2_dir\c.txt
======================================================================
1.txt 2.txt 3.txt 4.txt
======================================================================

 

디렉터리 삭제 shutil.rmtree()

shutil 모듈의 rmtree() 를 사용하면 디렉터리 안의 파일이 존재하더라도 삭제할 수 있습니다.

import shutil

print('-'*70)
file_list = os.listdir(dir_path)
print(*file_list)
print('-'*70)
for file in file_list:
    file_path = os.path.join(dir_path, file)
    if os.path.isdir(file_path):
        dir_path2 = file_path
        print(dir_path2)
        shutil.rmtree(dir_path2)
print('='*70)
file_list = os.listdir(dir_path)
print(*file_list)
print('='*70)
더보기
----------------------------------------------------------------------
1.txt 2.txt 3.txt test_dir2
----------------------------------------------------------------------
c:\Users\pju99\ex_os\test_dir\test_dir2
======================================================================
1.txt 2.txt 3.txt
======================================================================

 

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

 

파이썬 OS 모듈 사용하기 - 경로 합치기, 디렉터리/파일 확인, 경로 존재 확인 os.join() os.isdir() os.ex

경로 합치기 os.path.join(path1, path2, ...) 경로와 경로를 합치며 Windows(\), Linux(/) 에 모두 호환되므로, 경로를 합칠 때는 join() 을 쓰는 것을 추천합니다. path = os.getcwd() print(path) for file in..

jvvp.tistory.com

지난 포스트까지 pwd, cd, ls 의 명령어가 구현되었습니다.

이번 포스트에서 배운 삭제 명령어를 추가해보겠습니다.

import os
import shutil

cmd = {
    'pwd': os.getcwd,
    'cd': os.chdir,
    'ls': os.listdir,
    'rm': os.remove,
    'rmdir': shutil.rmtree
}
path = os.getcwd()
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)
        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)
            if os.path.isdir(p):
                rst = '[Dir]'
            else:
                rst = '[File]'
            print(f'{rst}\t{file}')
    elif splt[0] == 'rm':
        fname = splt[1]
        path = os.path.join(fname)
        if os.path.exists(path):
            if os.path.isfile(path):
                cmd['rm'](fname)
            else:
                print(f'[*] Error, {splt[1]} is dir.')
        else:
            print(f'[*] Error, Invalid file name : {splt[1]}')
    elif splt[0] == 'rmdir':
        dir_name = splt[1]
        path = os.path.join(dir_name)
        if os.path.exists(path):
            if os.path.isdir(path):
                if os.listdir(path):
                    print(f'[*] {dir_name} is not empty')
                    while True:
                        ip = input(f'[*] Delete all[y], No[n] >> ')
                        if ip == 'y':
                            cmd['rmdir'](dir_name)
                            break
                        elif ip == 'n':
                            break
                        else:
                            print('[*] y or n')
            else:
                print(f'[*] Error, {splt[1]} is file.')
        else:
            print(f'[*] Error, Invalid dir name : {splt[1]}')
더보기
>> ls
[Dir]   .vscode
[File]  ex1.py
[File]  ex2.py
[File]  ex3.py
[File]  ex4.py
[Dir]   test_dir
>> cd test_dir
>> ls
[File]  2.txt
[File]  3.txt
[Dir]   test_dir2
>> cd test_dir2
>> ls
[File]  a
[File]  b
[Dir]   test_dir3
>> rmdir test_dir3
[*] test_dir3 is not empty
[*] Delete all[y], No[n] >> n
>> ls   
[File]  a
[File]  b
[File]  test_dir3
>> rmdir test_dir3
[*] test_dir3 is not empty
[*] Delete all[y], No[n] >> y
>> ls
[File]  a
[File]  b
>> rm b
>> ls
[File]  a
>> cd ..
>> ls
[File]  2.txt
[File]  3.txt
[Dir]   test_dir2
>> quit