Contents
접기
File I/O
파일 오픈
파일 객체 = open(파일이름, 파일열기모드)
# 파일 생성
f = open("myfile.txt","w") # 해당 파일을 쓸 수 있는 file 객체를 반환한다.
# 권한을 위임 받음 open() -> 반납 close()
# 파일 생성 후 문자열 쓰기
f.write("Hello World")
f.close() # 파일 닫기
print("End")
# 파일 생성 후 한글이 포함된 문자열 쓰기
# f = open('myfile.txt','w') # err 한글이 정상적으로 쓰이지 않음
f = open('myfile.txt','w',encoding='utf-8') # err 한글이 정상적으로 쓰이지 않음
f.write("안녕하세요! Hi")
f.close()
print("End")
데이터 읽기
- readline() : 한 줄 읽어서 리턴, 파일 마지막에 도달하면 빈 문자열을 리턴한다.
- readlines() : 파일의 모든 라인을 읽어서 각각의 줄을 요소로 갖는 리스트로 리턴한다.
- read() : 파일의 내용 전체를 문자열로 리턴.
# 노래 가사 들어있던 파일
f = open("song.txt","r")
# data = f.read()
data = f.readlines()
print(data)
# ["Hello, it's me \n", "I was wondering if after all these years you'd like to meet\n",...]
f.close()
f = open("song.txt","r")
while True:
line = f.readline()
if not line: break
print(line,end='')
# Hello, it's me
# I was wondering if after all these years you'd like to meet
f.close()
데이터 저장/추가
파일을 오픈 할때 mode를 'w' 로 하면 저장, 'a' 로 하면 기존 내용에 추가
write(저장할 데이터)
score = {'홍길동':89,'임꺽정':78,'손오공':88,'전우치':90,'저팔계':90}
f = open("score.txt","w",encoding='utf-8')
for name,s in score.items():
f.write(f"{name}: {s}점\n")
f.write("=========================\n")
f.write(f"학생수: {len(score)}명\n")
f.write(f"합계: {sum(score.values())}\n") # 값만
f.write(f"평균: {sum(score.values())/len(score):}\n")
f.close()
print("End")
f = open("score.txt","a",encoding='utf-8')
f.write("=========================")
f.close()
print("end")
with 문 사용
with문을 사용하면 with블럭을 벗어나는 순간 파일 객체가 자동으로 닫힌다.
with open("score.txt","r",encoding="utf-8") as f:
# 변수 f 가 오픈 파일 받아온 것
text = f.read()
print(text)
print("end")
입출력 위치
현재 입출력 위치를 조사할 때는 tell 함수 사용.
위치를 변경할 때는 seek(위치,기준) 함수 (기준이 0: 파일 처음부터, 1: 현재기준, 2: 끝에서부터)
f = open("song.txt","r")
f.seek(4) # 파일 포인터 이동
text = f.read()
print(text)
# o, it's me
# I was wondering if after all these years you'd like to meet
f.close()
## 사진파일 복제
original = open("Python.jpg","rb") # r 만 쓰면 txt로 인식
target = open("copy_python.jpg","wb")
data = original.read()
target.write(data)
original.close()
target.close()
print("end")
OS모듈
경로면과 파일명에 대한 함수를 제공하는 모듈. 특정 경로에 대한 위치 파일과 디렉토리 목록을 구한다.
import os
path = r"g:\내 드라이브\DIMA3\01.Python" # r" " : 문자 그자체로 인식하게 해줌
os.chdir(path)
c_path = os.getcwd()
print("현재 작업 디렉토리:", c_path)
# os.chdir('..')
os.chdir("..")
print("상위디렉토리로 이동")
c_path = os.getcwd()
print("현재 작업 디렉토리:", c_path)
# 현재 작업 디렉토리: G:\내 드라이브\DIMA3\01.Python
# 상위디렉토리로 이동
# 현재 작업 디렉토리: G:\내 드라이브\DIMA3
# 파일 및 디렉토리 목록 반환
list = os.listdir() # 현재 경로에 있는 파일 목록
for item in list:
if os.path.isfile(item): # 파일인지 체크
print(f"[File]{item}, {os.path.getsize(item)}bytes")
else:
print(f"[Dir]{item}")
glob 모듈
패턴을 이용하여 파일을 검색할때 사용한다. (glob 함수에 파일명의 패턴이용)
import os
import glob
# 현재 디렉토리 내 모든 디렉토리만 출력: **/, */
for f in glob.glob('**/'):
print(f)
# subdir\
# banking\
# 현재 디렉토리와 파일 출력: ** , *
for f in glob.glob('**'):
print(f)
# Python 실습.ipynb
# Coding_Test_1.ipynb
# ...
# 하위 디렉토리에 있는 디렉토리와 파일 출력: **/** , */*
# 현재 디렉토리는 포함하지 않는다.
os.chdir("..")
for f in glob.glob('*/*'):
print(f)
# 현재 디렉토리 포함하여 하위 모든 디렉토리와 파일 출력
for i, f in enumerate(glob.glob("**", recursive= True)):
print(i,f)
'국비 교육 > 파이썬' 카테고리의 다른 글
[파이썬] Class (상속, 은닉) (0) | 2023.12.28 |
---|---|
[파이썬] 예외(Exception) (0) | 2023.12.28 |
[파이썬] 함수 - 2 (0) | 2023.11.05 |
[파이썬] 함수 -1 (0) | 2023.11.05 |