#파일 : 메모리가 아닌 디스크에 저장된 데이터의 집합
#텍스트 파일 : 저장된 데이터를 읽어서 텍스트로 디코딩해야 볼 수 있다
#이진 파일 : 텍스트 파일이 아닌 그 이외의 데이터를 저장한 파일 ( jpg,png... )
#mode :
1. r (읽기)
2. w (쓰기)
3. a (추가)
4. x (생성)
5. b (이진 데이터)
6. t (텍스트)
7. +
#mode 설정의 예 : r(rt) -> 테스트 읽기 / wb -> 이진데이터를 파일에 쓰겠다 / r+ -> 읽기도 하고 쓰겠다
#mode 생략 시 r모드
------------------------------------------------------------------------------------------------------------------------------------------
1. 파일 생성
fsteram = open('my_sample.txt','w',encoding='utf-8') #파일 열기 (파일 생성)
fsteram.write('내가 만든 파일 \n') #파일에 내용 넣기
fsteram.close() #열었던 파일 닫기
1-1. 절대 경로로 파일 생성
fsteram = open('D:/test/my_sample.txt','w',encoding='utf-8') #파일 열기 w->파일의 내용을 지우고 쓰기
fsteram.write('내가 만든 파일 \n')
fsteram.close()
#파일 기존 내용에 추가하려면 'a'모드 사용
#해당 파일이 없을때만 생성하려면 'x'를 생성
1-2. 파일 있는지 확인하고 생성
#지정 파일이 없는 경우에만 파일 생성하기
try:
with open('smaple.txt','x',encoding='utf-8') as fstream: #x-> 파일이 없을때만 실행
print('파일을 새로 생성합니다.')
except FileExistsError as fe: #FileExistsError 객체가 fe에 전달됨
print(fe)
print('이미 파일이 존재 합니다.') #이미 있는 경우 FileExistsError
finally: #무조건 실행
print('finally입니다.')
[Errno 17] File exists: 'smaple.txt'
이미 파일이 존재 합니다.
finally입니다.
------------------------------------------------------------------------------------------------------------------------------------------
2. 파일 내용 읽기( Read )
fsteram = open('my_sample.txt',encoding='utf-8') #파일 열기
data = fsteram.read() #파일 내용을 다 읽어옴
print(data)
fsteram.close()
2-1. 한 줄 읽기 ReadLine
with open("D:/test/emp.txt",encoding='utf-8') as fin:
print(type(fin)) #<class '_io.TextIOWrapper'>
while True:
line = fin.readline()
if line: #읽어 올 데이터가 없을때 ""반환 ( "" -> False )
print(line.strip())
else:
break
with open("D:/test/emp.txt",encoding='utf-8') as fin:
print( hasattr(fin,'__iter__')) #iter이면 바로 한행씩 가져오기 가능
for line in fin:
print(line.strip())
----------------------------------------------------------- Tip. 절대경로 지정하기 -------------------------------------------------------------------
#절대 경로 파일 내용 읽기
fsteram = open('D:/test/my_sample.txt',encoding='utf-8') ->추천
fsteram = open(r'D:\test\my_sample.txt',encoding='utf-8') # r-> 순수 문자열이다
fsteram = open('D:\\test\\my_sample.txt',encoding='utf-8')
------------------------------------------------------- Tip. with ( 자동 close )---------------------------------------------------------------
#파일을 열 때 with 블럭을 사용하면 블럭이 모두 실행된 후에 자동으로 close()된다
with open('my_sample.txt',encoding='utf-8') as fsteram: #파일 열기
data = fsteram.read() #파일 내용을 다 읽어옴
print(data)
-------------------------------------------------------< 파일인지, 디렉토리인지 확인 >-----------------------------------------------------------
import os
os.path.isfile( 'Day02.ipynb') #파일인가?
os.path.isdir( 'Day02.ipynb') #디렉토리인가?
------------------------------------------------------- Tip. 보기 쉽게 경로 지정 ( join ) -----------------------------------------------------------
import os
abspath = os.path.join("D:\\test","testfile.txt")
abspath
'D:\\test\\testfile.txt'
------------------------------------------------------- < 파일 Copy_Update_Delete >---------------------------------------------------------------
#파일 복사하기
import shutil
shutil.copy('src_file','dst_file')
# 파일명 변경
import os
os.rename('old_name','new_name')
#파일 삭제
import os
os.remove('file_name')
------------------------------------------------------- < 이진 파일을 읽기 쓰기 >---------------------------------------------------------------
# 이진 파일을 읽기 쓰기
fstream = open('sample.jpg','rb') # rb -> 읽어옴
data = fstream.read()
fstream.close()
fstream = open('sample_cpy.jpg','wb') # wb -> 쓰기 (새 파일이 생김 )
fstream.write(data)
fstream.close()
'Python공부' 카테고리의 다른 글
Python = Jupyter NoteBook에서 SQL사용하기,pandas ,with (0) | 2022.08.19 |
---|---|
Python - 날짜, 시간 (0) | 2022.08.17 |
Python - List, Dictionary, Tuple의 차이점 (0) | 2022.08.17 |
Python - 문자열,리스트,딕셔너리 관련 함수( next( ) , join(), items() , enumerate( ), reversed() ) (0) | 2022.08.17 |
Python - for문 심화 (거꾸로 반복_reversed) (0) | 2022.08.17 |