os.mkdir() : 디렉토리 생성
os.makedirs() : 인자로 받은 경로에 디렉토리 생성 (모든 경로 디렉토리 없으면 생성함)
import os
if os.path.exists('ex_folder'):
print('The folder already exists.')
else:
os.mkdir('ex_folder')
print('The folder has been created.')
os.makedirs('ex_folder/20240206')
shutil.copy() : 파일 복사
shutil.copytree() : 디렉토리 복사
import shutil
shutil.copytree('D:\ex_folder', 'ex_folder')
import shutil
shutil.copy('ex_folder/B.jpg', 'ex_folder/A.jpg')
shutil.rmtree() : 디렉토리와 포함된 내용 전체 삭제
os.remove() : 경로의 파일 삭제
import os
import shutil
os.remove('ex_folder/B.txt')
shutil.rmtree('ex_folder')
shutil.move() : 파일 또는 디렉토리 이동
import shutil
shutil.move('ex_folder/B.txt', 'ex_folder/a/B.txt')
os.path.split() 디렉토리와 파일 분리
os.path.splitext() 확장자만 분류
os.path.dirname() 디렉토리만 출력
os.path.basename() 파일이름 출력
os.path.isdir() 디렉토리인지 확인
os.path.walk(시작 디렉토리, 각 디렉토리마다 실행할 함수, 함수에 대한 인수)
os.path.exists() 파일의 존재 여부 확인
os.path.splitext(file)[0]
os.path.splitext()는 경로를 포함한 파일 이름과, 확장자를 튜플로 반환함.
import os
from collections import Counter
folder_path = 'ex_folder'
filenames = os.listdir(folder_path)
for name, count in Counter(os.path.splitext(file)[0] for file in filenames).items():
if count == 1:
single_files = [file for file in filenames if os.path.splitext(file)[0] == name]
if any(file.lower().endswith(('.jpg', '.jpeg', '.png', '.gif')) for file in single_files):
for file in single_files:
file_path = os.path.join(folder_path, file)
os.remove(file_path)
print(f"Removed: {file_path}")
from collections import Counter
import os
folder_path = 'ex_folder'
for dirpath, dirnames, filenames in os.walk(folder_path):
for file in filenames:
name = os.path.splitext(file)[0]
if Counter(os.path.splitext(f)[0] for f in filenames)[name] == 1:
file_path = os.path.join(dirpath, file)
if file.lower().endswith(('.jpg', '.jpeg', '.png', '.gif')):
os.remove(file_path)
print(f"Removed: {file_path}")
더 괜찮은 방법이 많이 있을 것 같은데
from collections import Counter
import os
folder_path = 'ex_folder'
txtfile2 = []
for dirpath, dirnames, filenames in os.walk(folder_path):
for file in filenames:
extention = os.path.splitext(file)[1]
if extention==".txt":
txtfile2.append(file)
print(len(txtfile2))
♬
os.listdir(): path 내 파일과 폴더 목록을 가져옴
os.path.join(path, x): 경로와 파일 또는 폴더 이름을 결합 = 전체 경로
os.path.isdir(x): x path가 폴더인지 확인
os.path.isfile(x): x path가 파일인지 확인
import os
failed_list = []
def walk(path):
contents = [os.path.join(path, x) for x in os.listdir(path)]
dirnames = [x for x in contents if os.path.isdir(x)]
filenames = [x for x in contents if os.path.isfile(x)]
for dirname in dirnames:
walk(dirname)
if not dirnames and not filenames:
try:
os.removedirs(path)
except:
failed_list.append(path)
walk('ex_folder')
print("Done")
https://www.w3schools.com/python/python_lists_comprehension.asp
Python - List Comprehension
W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.
www.w3schools.com