기타/파이썬

[Python] os, shutil 모듈 사용하기

푸쿠이 2021. 5. 16. 22:19

친구 과제 도와주다가 기록함.

import os
import shutil

# py파일이 있는 곳에 실습할 폴더 생성
# os.mkdir('실습 1') # 이미 폴더가 존재하면 오류남.
os.makedirs('실습 1', exist_ok=True) # 폴더가 없으면 생성. 있어도 오류 없음.
os.chdir('실습 1') # 실습 폴더로 이동

# 파일 생성
open('test1.txt', 'w') 
open('test2.txt', 'w')
open('test3.pptx', 'w')
open('test4.csv', 'w')

# 폴더 내의 모든 파일 리스트 출력
file_list = os.listdir();
print(file_list)

# 폴더 내의 .txt 파일 리스트 출력
file_list_txt = [file for file in file_list if file.endswith(".txt")]
print(file_list_txt)

# 아까 실습 폴더로 이동했으니, 그 위치에 test 폴더 만들기
os.makedirs('test', exist_ok=True) 

# test 폴더에 txt 파일 옮기기
for file in file_list_txt: # file_list_txt에 있는 요소들을 하나하나 옮김.
	shutil.move(file, 'test') # 이미 파일이 존재하면 오류 남.
    

# test 폴더 삭제
# os.rmdir('test') # 폴더가 비어있지 않으면 오류가 뜸.
os.system('rmdir /S /Q test') # 시스템 명령어로 강제 삭제.

 

여기서 오류 날 수도 있음.

# test 폴더에 txt 파일 옮기기
for file in file_list_txt: # file_list_txt에 있는 요소들을 하나하나 옮김.
    shutil.move(file, 'test') # 이미 파일이 존재하면 오류 남.

(test1.txt, test2.txt)를 test폴더에 옮기려고 하는데,

이미 test 폴더에 해당 파일이 존재하는 경우에 발생하는 오류이다.

raise Error("Destination path '%s' already exists" % real_dst)
shutil.Error: Destination path 'test\test1.txt' already exists

https://stackoverflow.com/questions/31813504/move-and-replace-if-same-file-name-already-exists

 

Move and replace if same file name already exists?

Here is below code which will move and replace individual file: import shutil import os src = 'scrFolder' dst = './dstFolder/' filelist = [] files = os.listdir( src ) for filename in files:

stackoverflow.com

전체 경로로 지정하면 파일을 덮어쓰기 때문에, 오류를 피할 수 있다고 한다.