대형 프로그램을 만들 때 일반적으로 대형 프로그램에 필요한 일부 데이터를 저장하기 위해 만들어야 하는 작은 파일이 있습니다. 프로그램이 완료되면 삭제해야 합니다. 이번 글에서는 파일을 삭제하는 방법에 대해 알아보겠습니다. 파이썬 .
Python에서 파일을 삭제하는 방법
- Python을 사용하여 파일 삭제 너. 제거하다
- 다음을 사용하여 Python에서 파일을 삭제합니다. send2trash 모듈
- Python을 사용하여 파일 삭제 os.rmdir
파일이 존재하는지 확인하세요.
OS 모듈을 설치하는 명령:
pip3 install os>
Python에서 파일 삭제의 경우 다음을 사용할 수 있습니다.os.path.exists()>파일이 있는지 확인하는 기능입니다. 간단한 예는 다음과 같습니다. 바꾸기'> path/to/your/file.txt> '>확인하려는 파일의 실제 경로를 사용하십시오. 그만큼os.path.exists()>함수 반환True>파일이 존재하고False>그렇지 않으면. 그런 다음 코드는 파일의 존재 여부에 따라 메시지를 인쇄합니다.
파이썬3
import> os> def> check_file_existence(file_path):> >if> os.path.exists(file_path):> >print>(f>'The file '{file_path}' exists.'>)> >else>:> >print>(f>'The file '{file_path}' does not exist.'>)> # Example usage:> file_path>=> 'path/to/your/file.txt'> check_file_existence(file_path)> |
>
>
인터페이스 vs 추상 클래스
출력 :
The file 'path/to/your/file.txt' does not exist.>
'os.remove'를 사용하여 Python에서 파일 삭제
우리는 OS 라이브러리를 가져와서 사용할 것입니다. os.remove() 함수 원하는 파일을 제거하려면
예 1: 현재 디렉터리에서 파일 삭제
현재 디렉터리에서 파일을 삭제하는 간단한 코드입니다.
파이썬3
import> os> os.remove(>'starwars.txt'>)> |
>
>
예시 2: 자세한 설명
아래 코드에서 Python 스크립트는 사용자에게 삭제할 파일 이름을 입력하라는 메시지를 표시합니다. 입력이 'quit'이면 프로그램이 종료됩니다. 그렇지 않으면 `os.remove()`를 사용하여 지정된 파일을 제거하려고 시도합니다. 그러면 성공 메시지가 인쇄됩니다.
파이썬3
import> os> print>(>'Enter 'quit' for exiting the program'>)> filename>=> input>('Enter the name of the>file>,> >that>is> to be deleted : ')> if> filename>=>=> 'quit'>:> >exit()> else>:> >print>(>'
Starting the removal of the file !'>)> >os.remove(filename)> >print>(>'
File, '>, filename, 'The>file> deletion> >is> successfully completed !!')> |
>
>
산출:
삭제하려는 파일:

프로그램의 샘플 실행

삭제할 파일 이름을 입력하면:

삭제:

작업 결과:

send2trash 모듈을 사용하여 Python에서 파일 삭제
우리는 os.walk() 함수 디렉토리를 탐색하고 특정 파일을 삭제합니다. 아래 예에서는 해당 디렉터리의 모든 '.txt' 파일을 삭제합니다.
예 : 이 스크립트에서는 `os.walk`를 사용하여 '/Users/tithighosh/Documents' 디렉터리의 파일을 살펴봅니다. 발견된 각 '.txt' 파일에 대해 해당 경로를 인쇄하고 'send2trash'를 사용하여 해당 파일을 시스템 휴지통으로 이동하여 영구 삭제를 방지합니다. 스크립트는 지정된 디렉터리와 하위 디렉터리에 있는 모든 '.txt' 파일을 효과적으로 삭제합니다.
파이썬3
import> os> import> send2trash> # walking through the directory> for> folder, subfolders, files>in> os.walk(>'/Users/tithighosh/Documents'>):> > >for> file> in> files:> > ># checking if file is of .txt type> >if> file>.endswith(>'.txt'>):> >path>=> os.path.join(folder,>file>)> > ># printing the path of the file> ># to be deleted> >print>(>'deleted : '>, path )> > ># deleting the file> >send2trash.send2trash(path)> |
>
>
for 루프 자바
산출:
deleted : /Users/tithighosh/Documents/cfile.txt deleted : /Users/tithighosh/Documents/e_also_big_output.txt deleted : /Users/tithighosh/Documents/res.txt deleted : /Users/tithighosh/Documents/tk.txt>
os.rmdir을 사용하여 Python에서 파일 삭제
에서os.rmdir>메소드는 주어진 경로에 지정된 빈 디렉토리를 제거합니다. 디렉터리에 파일이나 하위 디렉터리가 포함되어 있으면 메서드에서 OSError가 발생한다는 점에 유의하는 것이 중요합니다. 따라서 이 방법을 사용하기 전에 디렉터리가 비어 있는지 확인하는 것이 중요합니다.
예 : 이 예에서는'path/to/empty_directory'>삭제하려는 빈 디렉터리의 실제 경로를 사용하세요. 그만큼delete_empty_directory>함수는 다음을 사용하여 지정된 디렉터리를 제거하려고 시도합니다.os.rmdir>삭제가 성공하면 성공 메시지를 인쇄합니다.
파이썬3
import> os> def> delete_empty_directory(directory_path):> >try>:> >os.rmdir(directory_path)> >print>(f>'The directory '{directory_path}' has been successfully deleted.'>)> >except> OSError as e:> >print>(f>'Error: {e}'>)> # Example usage:> directory_to_delete>=> 'path/to/empty_directory'> delete_empty_directory(directory_to_delete)> |
>
>
출력 :
The directory 'path/to/empty_directory' has been successfully deleted.>
관련 기사
Python에서 N일보다 오래된 파일 삭제