Python

[Python] module 사용 종합 버전(json, os, dict, shutil, string)

sorry0101 2023. 7. 27. 17:44
import json
import os.path
import shutil

'''json'''
# 읽기
with open('경로', "r") as file:
    json_data = json.load(file)
    
# 쓰기
with open('경로', "w") as file:
    json.dump(json_data, file, indent="\t") # indent = "\t" : 들여쓰기 포함


'''os'''
# 디렉토리 생성
os.makedirs('경로')

# 경로 존재 확인
if os.path.exists('경로'):
	print("있다")

# 해당 경로에 있는거 열기
os.startfile('경로')
    
# 절대 경로 찾기
os.path.abspath('경로')

# 파일 제거
os.remove('경로')

# 경로의 하위 폴더들만 가져오기
os.listdir('경로')

# 하위 전체 경로 검색
for (path, dirs, files) in os.walk(currentPath):
    for dir in dirs:
        print(dir)
    for filename in files:
        print(filename)

# 상위 경로 찾기
os.path.dirname('경로')

# 현재 위치한 상위 경로
os.getcwd()


'''dictionary'''
my_dict = dict()

# 추가
my_dict['hi'] = 'yes'
my_dict['hello'] = 'no'

 # 제거
del(my_dict['hi'])

# 항목 존재 확인
if my_dict.get('hi') is not None:
	print("없어")
    
# key val 찾기
for key, value in my_dict.items():
	print(key)
    print(value)
    
# key 찾기
for key in my_dict:
	print(key)
    
# value 찾기
for value in my_dict.values():
	print(value)


'''shutil'''
# 폴더 제거 (하위 포함 전부 다)
shutil.rmtree('경로')

# 폴더 복제(경로가 길 경우 앞에 "\\\\?\\" 추가)
# 참고 : https://stackoverflow.com/questions/14075465/copy-a-file-with-a-too-long-path-to-another-directory-in-python
shutil.copytree(from_path, to_path)

# 권한까지 복제
# src => source, dst => destination
shutil.copy2(src, dst)

# 파일 복제
shutil.copyfile(from_file, to_file)


'''string'''
# 맨 앞글자만 대문자
filename = 'hansol'
filename.capitalize() # Hansol

# 시작하는 단어 확인
if filename.startswith('han'):
	print("맞다")
    
# 특정 단어 포함 갯수
word = 'aabbbc'
word.count('a') # 2