티스토리 뷰
반응형
Python 에서는 파일(File)을 생성하거나 읽고, 수정 및 삭제할 수 있습니다.
파일처리는:
- 로그 저장
- 설정 파일 관리
- CSV 데이터 처리
- 텍스트 저장
- 업로드 파일 관리
등 다양한 작업에서 사용됩니다.
파일처리 기본 개념
Python 파일처리는 보통 아래 순서로 진행합니다.
1. 파일 열기(open)
2. 파일 읽기/쓰기
3. 파일 닫기(close)
open() 함수
파일 열기 시 사용.
기본 구조:
open(파일명, 모드)
파일 열기 모드
| r | 읽기(Read) |
| w | 쓰기(Write) |
| a | 추가(Append) |
| x | 파일 생성(Create) |
| b | 바이너리(Binary) |
| t | 텍스트(Text) |
파일 쓰기(write)
새 파일 생성
file = open("test.txt", "w")
file.write("Hello Python")
file.close()
실행 후:
test.txt
파일 생성됨.
한글 저장
file = open("test.txt", "w", encoding="utf-8")
file.write("안녕하세요")
file.close()
Windows에서는 한글 깨짐 방지를 위해:
encoding="utf-8"
사용 권장.
파일 읽기(read)
file = open("test.txt", "r", encoding="utf-8")
text = file.read()
print(text)
file.close()
결과:
안녕하세요
한 줄씩 읽기(readline)
file = open("test.txt", "r", encoding="utf-8")
line = file.readline()
print(line)
file.close()
여러 줄 읽기(readlines)
file = open("test.txt", "r", encoding="utf-8")
lines = file.readlines()
print(lines)
file.close()
결과 예시:
['첫번째\n', '두번째\n']
반복문으로 파일 읽기
file = open("test.txt", "r", encoding="utf-8")
for line in file:
print(line)
file.close()
파일 추가 모드(a)
기존 내용 유지 후 뒤에 추가.
file = open("test.txt", "a", encoding="utf-8")
file.write("\n추가 내용")
file.close()
with 문 사용
가장 많이 사용하는 방식.
장점:
- 자동 close 처리
- 코드 간결
with 예제
with open("test.txt", "r", encoding="utf-8") as file:
text = file.read()
print(text)
파일 존재 여부 확인
import os
print(os.path.exists("test.txt"))
결과:
True
파일 삭제
import os
os.remove("test.txt")
폴더 생성
import os
os.mkdir("data")
폴더 존재 여부 확인
import os
print(os.path.isdir("data"))
현재 폴더 확인
import os
print(os.getcwd())
파일명 목록 조회
import os
files = os.listdir()
print(files)
CSV 파일 처리
CSV:
쉼표(,) 기반 데이터 파일
CSV 저장
import csv
with open("data.csv", "w", newline="", encoding="utf-8") as file:
writer = csv.writer(file)
writer.writerow(["이름", "나이"])
writer.writerow(["홍길동", 30])
CSV 읽기
import csv
with open("data.csv", "r", encoding="utf-8") as file:
reader = csv.reader(file)
for row in reader:
print(row)
결과:
['이름', '나이']
['홍길동', '30']
JSON 파일 처리
JSON:
데이터 교환용 형식
JSON 저장
import json
data = {
"name": "홍길동",
"age": 30
}
with open("data.json", "w", encoding="utf-8") as file:
json.dump(data, file, ensure_ascii=False)
JSON 읽기
import json
with open("data.json", "r", encoding="utf-8") as file:
data = json.load(file)
print(data)
결과:
{'name': '홍길동', 'age': 30}
바이너리 파일 처리
이미지, 영상 등 처리 시 사용.
바이너리 쓰기
file = open("sample.bin", "wb")
file.write(b"hello")
file.close()
바이너리 읽기
file = open("sample.bin", "rb")
data = file.read()
print(data)
file.close()
결과:
b'hello'
파일처리 실전 예제
메모장 저장 프로그램
text = input("내용 입력:")
with open("memo.txt", "a", encoding="utf-8") as file:
file.write(text + "\n")
로그 저장
from datetime import datetime
with open("log.txt", "a", encoding="utf-8") as file:
file.write(str(datetime.now()) + "\n")
자주 발생하는 오류
파일 없음 오류
open("none.txt", "r")
오류:
FileNotFoundError
인코딩 오류
한글 파일 처리 시:
encoding="utf-8"
권장.
close 누락
file.close()
누락 시 파일 잠금 발생 가능.
실무에서는:
with open()
사용 권장.
#Python
#Python파일처리
#PythonFile
#PythonOpen
#PythonCSV
#PythonJSON
#Python텍스트파일
#파이썬파일처리
#Python기초
#Python문법
'Python' 카테고리의 다른 글
| Python 함수(Function) 정리 (0) | 2026.05.30 |
|---|---|
| Python 반복문(Loop) 정리 (0) | 2026.05.29 |
| Python DB 연결 방법 (0) | 2026.05.28 |
| Python 조건문(Conditional Statement) 정리 (0) | 2026.05.27 |
| Python 변수(Variable) 정리 (0) | 2026.05.26 |
| Python 설치 방법 (Windows 환경) (0) | 2026.05.25 |
| 내 Python 프로젝트에 OpenAI API를 활용하기 STEP.5 (0) | 2026.05.02 |
| 내 Python 프로젝트에 OpenAI API를 활용하기 STEP.4 (0) | 2026.05.02 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- DB연동
- 문제풀이
- 알고리즘
- OpenCV
- 안드로이드
- C
- C++ 클래스
- C++
- html
- MySQL
- Java
- 블루투스
- 상속
- Android
- C언어
- 자료구조
- 배열
- 클래스
- 정보처리기사
- String
- Class
- 데이터베이스
- 파이썬
- 파일처리
- c#
- 아두이노
- 벡터
- 자바
- 리스트
- 문자열
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | 6 | |
| 7 | 8 | 9 | 10 | 11 | 12 | 13 |
| 14 | 15 | 16 | 17 | 18 | 19 | 20 |
| 21 | 22 | 23 | 24 | 25 | 26 | 27 |
| 28 | 29 | 30 |
글 보관함
반응형
