You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
# 파일 열기 -> 작업 -> 닫기파일객체=open(파일이름, 파일열기모드)
# 파일 사용 (읽기 또는 쓰기)파일객체.close() # 반드시 닫아야 함!
2. CSV와 TSV 파일
2.1 CSV (Comma Separated Value)
데이터가 **쉼표(,)**로 구분된 포맷입니다.
Name,Age,City
Alice,25,New York
Bob,30,London
2.2 TSV (Tab Separated Value)
데이터가 **탭(\t)**으로 구분된 포맷입니다.
Name Age City
Alice 25 New York
Bob 30 London
2.3 CSV vs TSV 비교
항목
CSV
TSV
구분자
쉼표 (,)
탭 (\t)
확장자
.csv
.tsv
장점
범용적, Excel 호환
데이터에 쉼표 포함 가능
단점
데이터에 쉼표 포함 시 따옴표 필요
시각적 정렬이 어려움
용도
일반 데이터
텍스트 데이터, 로그
3. 파일 열기 모드
3.1 기본 모드
모드
설명
파일 없을 때
기존 내용
r
읽기 모드
FileNotFoundError
유지
w
쓰기 모드
새로 생성
덮어쓰기
a
추가 모드
새로 생성
유지 (끝에 추가)
x
배타적 생성
새로 생성
FileExistsError (파일 있으면)
3.2 바이너리 모드
모드
설명
rb
바이너리 읽기
wb
바이너리 쓰기
ab
바이너리 추가
3.3 읽기+쓰기 모드
모드
설명
r+
읽기+쓰기 (파일 있어야 함)
w+
쓰기+읽기 (기존 내용 삭제)
a+
추가+읽기 (끝에 추가)
3.4 모드 사용 예시
# 읽기 모드 - 파일이 없으면 에러f=open("data.txt", "r")
# 쓰기 모드 - 기존 내용 삭제됨f=open("data.txt", "w")
# 추가 모드 - 기존 내용 뒤에 추가f=open("data.txt", "a")
# 바이너리 모드 - 이미지, 동영상 등f=open("image.png", "rb")
4. 파일 읽기
4.1 readline() - 한 줄씩 읽기
파일에서 한 줄씩 읽어옵니다.
f=open("새파일.txt", "r")
line=f.readline()
print(line) # 첫 번째 줄line=f.readline()
print(line) # 두 번째 줄f.close()
4.2 read() - 전체 읽기
파일 전체 내용을 문자열로 읽어옵니다.
f=open("새파일.txt", "r")
data=f.read() # 전체 내용을 하나의 문자열로print(data)
f.close()
# while 반복문f=open("새파일.txt", "r")
whileTrue:
line=f.readline()
ifnotline: # 더 이상 읽을 줄이 없으면 종료breakprint(line, end="") # 자동으로 추가되는 줄바꿈 제거f.close()
# for 반복문 (가장 권장)f=open("새파일.txt", "r")
forlineinf: # 파일 객체는 iterableprint(line, end="")
f.close()
4.6 읽기 메서드 비교
메서드
반환 타입
특징
메모리
read()
문자열
전체 내용
많이 사용
read(n)
문자열
n자만 읽기
효율적
readline()
문자열
한 줄
효율적
readlines()
리스트
모든 줄
많이 사용
for line in f
반복자
한 줄씩
가장 효율적
5. 파일 쓰기와 추가
5.1 write() - 문자열 쓰기
# 쓰기 모드 (w) - 기존 내용 삭제f=open("새파일.txt", "w")
foriinrange(1, 6):
f.write(f"{i} Line\n") # 줄바꿈은 직접 추가해야 함f.close()
# 결과:# 1 Line# 2 Line# 3 Line# 4 Line# 5 Line
5.2 추가 모드 (a)
# 추가 모드 (a) - 기존 내용 뒤에 추가f=open("새파일.txt", "a")
foriinrange(6, 11):
f.write(f"{i} Line append\n")
f.close()
# 기존 내용 뒤에 추가됨:# 1 Line# 2 Line# ...# 6 Line append# 7 Line append# ...
5.3 writelines() - 리스트 쓰기
f=open("새파일.txt", "w")
lines= ["첫 번째 줄\n", "두 번째 줄\n", "세 번째 줄\n"]
f.writelines(lines) # 리스트의 각 요소를 파일에 씀f.close()
5.4 print() 함수로 파일 쓰기
f=open("새파일.txt", "w")
print("Hello, World!", file=f) # file 매개변수로 출력 대상 지정print("Python is fun!", file=f)
f.close()
6. with 구문
6.1 with 구문의 장점
close()를 자동 호출
예외 발생 시에도 파일이 안전하게 닫힘
코드가 더 간결하고 안전함
6.2 기본 사용법
# with 구문 사용 (권장)withopen("새파일.txt", "r") asf:
data=f.read()
print(data)
# 블록을 벗어나면 자동으로 f.close() 호출# 기존 방식 (비권장)f=open("새파일.txt", "r")
try:
data=f.read()
print(data)
finally:
f.close()
6.3 파일 읽기 with 구문
# 전체 읽기withopen("새파일.txt", "r") asf:
data=f.read()
print(data)
# 줄 단위 읽기withopen("새파일.txt", "r") asf:
forlineinf:
print(line, end="")
6.4 파일 쓰기 with 구문
withopen("새파일.txt", "w") asf:
foriinrange(1, 11):
f.write(f"{i} 번째 줄입니다.\n")
6.5 여러 파일 동시 열기
# 두 파일을 동시에 열기withopen("input.txt", "r") asinfile, open("output.txt", "w") asoutfile:
forlineininfile:
outfile.write(line.upper()) # 대문자로 변환하여 저장
7. csv 모듈 사용
7.1 csv 모듈 import
importcsv
7.2 CSV 파일 쓰기
importcsvdata= [
["Name", "Age", "City"],
["Alice", 25, "New York"],
["Bob", 30, "London"],
["Charlie", 35, "Paris"]
]
withopen("data.csv", "w", newline="") asfile:
writer=csv.writer(file)
writer.writerows(data) # 여러 행 한번에 쓰기# 결과 파일 (data.csv):# Name,Age,City# Alice,25,New York# Bob,30,London# Charlie,35,Paris
# UTF-8로 파일 읽기 (Mac/Linux 기본)withopen("파일.txt", "r", encoding="utf-8") asf:
data=f.read()
# CP949로 파일 읽기 (Windows 한글)withopen("파일.txt", "r", encoding="cp949") asf:
data=f.read()
# UTF-8로 파일 쓰기withopen("파일.txt", "w", encoding="utf-8") asf:
f.write("안녕하세요")
8.5 인코딩 에러 처리
# 에러 무시withopen("파일.txt", "r", encoding="utf-8", errors="ignore") asf:
data=f.read()
# 에러 문자 대체withopen("파일.txt", "r", encoding="utf-8", errors="replace") asf:
data=f.read() # 읽을 수 없는 문자는 ?로 대체
importosbase_path=r"/content/drive/MyDrive/[AI]"target_dir=os.path.join(base_path, "out")
# 디렉토리 존재 확인 후 생성ifnotos.path.exists(target_dir):
os.mkdir(target_dir) # 단일 디렉토리 생성print("디렉토리 생성 완료")
else:
print("디렉토리 이미 존재")
# 중첩 디렉토리 생성nested_dir=os.path.join(base_path, "a/b/c")
os.makedirs(nested_dir, exist_ok=True) # exist_ok=True: 이미 있어도 에러 없음