🔥_Programming/Python

[Python] 파일 이동, 복사, 삭제

쩡지 2022. 4. 22. 15:29

파일작업에 유용한 os 모듈을 소개한다.

 

예시로 보여드릴 작업 디렉토리의 구조는 다음과 같습니다.

※ 참고 - 디렉토리 구조 그리기: https://jeeuney.tistory.com/19?category=933290

현재 작업위치(working directory) 확인
import os

path = os. getcwd()
print(path)

▶ D:\TEST 

 

작업위치 변경 
import os

os.chdir("./test01") #os.chdir("D:/TEST/test01")

path = os.getcwd()
print(path)

▶ D:\TEST\test01

현재 경로는 "." 으로 간단하게 표현할 수 있다. (os.chdir 명령어를 쓰기 전, 현재 경로는 D:\TEST)

 

현재 경로의 파일 리스트 확인
import os

#현재 경로 : D:/TEST/test01

print(os.listdir())

▶ ['test01_a', 'test01_b', 'test01_c.txt']

os.listdir 명령어를 이용하면 해당 경로의 폴더/파일 목록을 리스트 형태로 얻을 수 있다.

 

파일 경로에서 폴더와 파일명 얻기
import os

dir,file = os.path.split("D:/TEST/test01/test01_c.txt")
print(dir)
print(file)

▶D:/TEST/test01

▶test01_c.txt

 

파일 이름 변경

D:/TEST/test02 폴더에 있는 test02_a.txt 파일 이름을 test02_A.txt 파일로 변경해보자.

import os

print(os.listdir("D:/TEST/test02")) #변경 전

os.renames("D:/TEST/test02/test02_a.txt", "D:/TEST/test02/test02_A.txt") #변경

print(os.listdir("D:/TEST/test02")) #변경 후

 

▶['test02_a.txt', 'test02_b.txt', 'test02_c.txt']

▶['test02_A.txt', 'test02_b.txt', 'test02_c.txt']