파이썬의 장점 중 하나는 일률적인 업무를 돕는 프로그램을 쉽게 만들 수 있다는 점이다. 이런 것이 가능한 이유는 파일과 디렉터리를 쉽게 관리할 수 있기 때문이다. 파일, 디렉터리 관리와 관련된 패키지는 os, shutil이다. 각각 용도에 따라 다르게 사용된다.
# file Detection
import os
path = "C:\\Users\\User\\Desktop\\test.txt"
if os.path.exists(path):
print("That location exists!")
if os.path.isfile(path):
print("That is a file")
elif os.path.isdir(path):
print("That is a directory!")
else:
print("That location doesn't exist!")
# file Read
try:
with open('test.txt') as file:
print(file.read())
except FileNotFoundError:
print("That file was not found :(")
# file Write
text = "Yooooooooo\nThis is some text\nHave a good one!\n"
with open('test.txt','w') as file:
file.write(text)
# file copy
# copyfile() = copies contents of a file
# copy() = copyfile() + permission mode + destination can be a directory
# copy2() = copy() + copies metadata (file’s creation and modification times)
import shutil
shutil.copyfile('test.txt','copy.txt') #src,dst
# file move
import os
source = "C:\\Users\\User\\Desktop\\source.txt"
destination = "C:\\Users\\User\\Desktop\\destination.txt"
try:
if os.path.exists(destination):
print("There is already a file there")
else:
os.replace(source,destination)
print(source+" was moved")
except FileNotFoundError:
print(source+" was not found")
# file delete
import os
import shutil
path = "test.txt"
try:
os.remove(path) #delete a file
#os.rmdir(path) #delete an empty directory
#shutil.rmtree(path)#delete a directory containing files
except FileNotFoundError:
print("That file was not found")
except PermissionError:
print("You do not have permission to delete that")
except OSError:
print("You cannot delete that using that function")
else:
print(path+" was deleted")
참고
[Python] 파이썬 하위 디렉토리(파일) 검색하는 방법
[Python] 파이썬 디렉토리 및 파일 전체를 복사 또는 일괄 삭제하는 방법 shutil.copytree(), shutil.rmtree()
[Python] 파이썬 파일 및 디렉토리(폴더) 삭제방법 : 파일, 디렉토리 무조건 삭제 하는 방법 : shutil , os
[Python] 파이썬 파일(디렉토리)처리 총정리: 경로 확인,경로 변경, 파일이름 변경

'개발자 > 파이썬 Python' 카테고리의 다른 글
| 중요한 Pandas 패키지 매쏘드 (0) | 2023.01.12 |
|---|---|
| openpyxl 파이썬에서 엑셀 업무 자동화 사용법 (0) | 2023.01.10 |
| jupyter notebook 모듈 설치 안될 때 초간단 해결 (0) | 2023.01.08 |
| python-pptx 파워포인트 문서 자동화 placeholder 정리 (0) | 2023.01.03 |
| 파이썬 pptx 파일 자동화 python-pptx 라이브러리 (0) | 2022.12.29 |
| 파이썬 퀴즈 문제 만들고 정답 확인하는 코드 (0) | 2022.12.27 |
| 파이썬 가위 바위 보 게임 코드 (1) | 2022.12.26 |
| 블로그 제목 파일로 저장하기 2 (1) | 2022.11.28 |
취업, 창업의 막막함, 외주 관리, 제품 부재!
당신의 고민은 무엇입니까? 현실과 동떨어진 교육, 실패만 반복하는 외주 계약,
아이디어는 있지만 구현할 기술이 없는 막막함.
우리는 알고 있습니다. 문제의 원인은 '명확한 학습, 실전 경험과 신뢰할 수 있는 기술력의 부재'에서 시작됩니다.
이제 고민을 멈추고, 캐어랩을 만나세요!
코딩(펌웨어), 전자부품과 디지털 회로설계, PCB 설계 제작, 고객(시장/수출) 발굴과 마케팅 전략으로 당신을 지원합니다.
제품 설계의 고수는 성공이 만든 게 아니라 실패가 만듭니다. 아이디어를 양산 가능한 제품으로!
귀사의 제품을 만드세요. 교육과 개발 실적으로 신뢰할 수 있는 파트너를 확보하세요.
지난 30년 여정, 캐어랩이 얻은 모든 것을 함께 나누고 싶습니다.
귀사가 성공하기까지의 긴 고난의 시간을 캐어랩과 함께 하세요.
캐어랩