python을 사용해서 자동으로 파일을 분류해주는 프로그램을 만들어봅니다.
1. anaconda jupyter 노트북을 사용해서 os 와 shutil 라이브러리를 불러와봅니다.
import os, shutil
#operating sytem, and high level operation on our files
1) os : used to load files into the notebook
2) shutil: 고수준의 파일을 연산함, 예를 들어 copy, create, delete, Remote 등
2. path 정해주기(고수준 연산을 하고 싶은 파일 명을 잡아준다.)
In [7]
path = f'/Users/grace/Desktop/파일명'
In [8]:
3. 파일명 정해주기
file_name= os.listdir(path)
#showing what is in the path folder,
1) 현 파일 상황 알기: listdir => 아마 list directory 라는 뜻으로 사용되는 듯, 그래서 현 path 안에 들어있는 파일을 보여주렴 이라는 뜻
create folder or check folder to see if it is there
In [5]:
4. for 문 반복해서 file 분류하기
#make folders in the files
folder_names = ['csv files','img files','text files']
for loop in range(0,3):
if not os.path.exists(path + folder_names[loop]):
os.makedirs(path + folder_names[loop])
for file in file_name:
if ".csv" in file and not os.path.exists(path+ "csv files/" +file):
#second one needs to be moved to the second index
shutil.move(path+file, path+ "csv files/" +file)
elif ".jpg" in file and not os.path.exists(path+ "img files/" +file):
#second one needs to be moved to the second index
shutil.move(path+file, path+ "img files/" +file)
elif ".txt" in file and not os.path.exists(path+ "txt files/" +file):
#second one needs to be moved to the second index
shutil.move(path+file, path+ "txt files/" +file)
1) 폴더 네임을 리스트로 만들고 os.path안에 없을 때에는 폴더 명을 생성해라(makedirs => 아마 make directory라는 뜻)
2) for문을 사용해서 file_name 안에 있는 모든 file 수색 => 만약 mother folder에 csv 파일이 있지만, 새로 생성된 csv files 란 파일에 없다면, 이제 shutil을 사용해서 연산해준다. 그렇다. shutil.move를 사용해서 원래 mother folder에서 새로 생긴 딸 폴더에 넣어줌
그러면 폴더 내 새로운 폴더가 생성되고 모든 파일들이 검열되기 시작하면서 파일이 제자리를 찾아감. 신기하다.
끗.
출처: Alex the analyst
'Programming > python' 카테고리의 다른 글
[python] pandas indexes (0) | 2023.06.01 |
---|---|
[python] Pandas Filtering and Ordering (0) | 2023.05.31 |
[알고리즘] 파이썬 문법 (0) | 2023.04.10 |
[웹 스크래핑] (0) | 2023.04.01 |
[matplotlib] 여러 그래프 (0) | 2023.03.27 |