[python] path & file

moon·2022년 1월 7일

Tools

목록 보기
1/1

path

os

import os

os.listdir(path) # 하위 폴더, 파일 모두 리스트로 반환

os.path.join(path1, path2) # return full path (경로 구분자는 실행 os에 따라)

os.path.isdir(path)
os.path.isfile(path)
os.path.splitext(path) # 파일명, 확장자 (.py) 로 구분

glob

UNIX shell이 사용하는 패턴을 이용할 때 사용하는 모듈

import glob

glob.glob("*.py", recursive=True)

shutil

module for file copy / move /

import shutil

shutil.move(src, dst)

pathlib

pathlib는 file path를 문자열이 아닌 객체로 다루는 모듈이다.

https://wikidocs.net/110182

file

pandas

csv, json, html, excel, pickle, sql 등 모두
pd.read_( ) pd.to_( ) 형태

  1. csv
    read_csv(path, index_col, date_parser)
    index_col : 인덱스로 설정할 column 지정
    date_parser : Timestamp 타입으로 변환할 column

  2. json
    read_json() to_json()

  3. pickle
    read_pickle() to_pickle()

pickle

python에서 사용하는 dictionary, list, class 등의 자료형을 변환 없이 그대로 파일로 저장하고 불러오기 위한 모듈이다.

- pickle file filename.p
- pickle 데이터는 binary data이기 때문에, pickle 파일을 binary mode로 열어서 pickle.load pickle.dump 를 통해 data type을 변환해줘야 한다.

import pickle

with open('filename.p', 'wb') as f :
	pickle.dump(dictionary, f)
    
with open('filename.p', 'rb') as f :
	dictionary = pickle.load(f)

0개의 댓글