본문 바로가기

CS/Python & C++

파일 다루기

파이썬으로 개발하다보면 로컬에서 테스트 하는 경웨 폴더안의 파일들을 찾고 읽고 쓰는 것과 관련한 코드들을 체감상 가장 많이 사용하는 것 같다.

많이 사용하는 것 만큼 외워질 정도로 체화가 되면 생산성이 급증한다.

 

1. 특정 폴더 안의 모든 파일 가져오기

import os
import json

read_folder_path = "example/path/example"
file_path_l = [os.path.join(read_folder_path, file_n) for file_n in os.listdir(read_folder_path)]

for file_path in file_path_l:
	with open(file_path, "r", encoding="utf-8") as rd:
    	text_data = rd.read()
        #json_data = json.load(rd)

 

 

2. 현재 리스트로 파일 작성하기

import os
import json

write_path = "example/path/example"
file_l = [str, json, ...]

for i in range(len(file_l)):
	with open(os.path.join(write_path, i+".확장자"), "w", encoding="utf-8") as wr:
    	wr.write(file_l[i])
        # wr.write(json.dumps(file_l[i]))
        # json.dump(file_l[i], wr)

 

3. 파일 이름, 부모 폴더 이름, 파일 이름과 확장자 분리

import os

read_folder_path = "example/path/example"
file_path_l = [os.path.join(read_folder_path, file_n) for file_n in os.listdir(read_folder_path)]

for file_path in file_path_l:
    folder_name = os.path.basename(os.path.dirname(file_path))
    file_name = os.path.basename(file_path)
    file_n, ext_n = os.path.splitext(os.path.basename(file_path))

 

4. 현재 파일의 실행 경로를 기준으로 상대경로를 절대경로로 만들기

import os

relative_path = "../"
file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), relative_path)

'CS > Python & C++' 카테고리의 다른 글

LLM을 활용한 코드리뷰 자동화  (1) 2025.04.27
병렬 처리  (0) 2025.01.21
람다 식(Lambda Expression)과 STL 알고리즘  (0) 2024.03.04
C++의 문자열 std::string  (0) 2024.02.15
이동 생성자 & 이동 대입 연산자  (0) 2024.01.29