[Python] 중급
텍스트 파일 쓰기
텍스트 파일 열기
with~eas문
writelines()
readlines(),readline()
기본 함수
open(),read(),write(),close()를 이용한 텍스트 파일 다루기
- 파일 쓰기
-writ()함수를 이용한 파일에 문자열 쓰기
-open('C:/pythonTxt/test.txt','w')
1)만약 test.txt파일을 새로 만들경우에는 ,
기존 파일이 없으면 새로 생성하고 텍스트 넣음
2)기존의 텍스트가 있었다면 삭제하고, 새로운 텍스트로 대체된다.import time lt=time.localtime() dateStr='[' +str(lt.tm_year) +'년'+\ str(lt.tm_mon) +'월'+str(lt.tm_mday)+'일]' # 동일한 표현 dateStr='['+time.strftime('%Y-%m-%d %H:%M:%S %p')+']' todatySchedule=input('오늘 일정:') file =open('C:/pythonTxt/test.txt','w') file.write(dateStr+todatySchedule) file.close()➜ time.strftime은 시간의 형태를 정할 수 있는 함수
➜ %Y:년 , %m:월 , %d:일 , %H:시간(13시)/%I(1시),
%M:분 , %S:초 , %p:pm/am
- 파일 읽기
read()함수를 이용한 파일 문자열 읽기
file =open('C:/pythonTxt/test.txt','r') str =file.read() print(str) file.close()➜ 기존 텍스트의 일부 텍스트의 변경이 필요할때,
1) 기존파일 'r'모드로 열기
2) 변수명.replace('기존문자','변경할문자',몇글자 변경할지 기입)
3) 해당파일 'w'모드로 열기 => 'w'기존 텍스트 대체하는 기능을 위함file = open('C:/pythonTxt/about_python.txt','r',encoding='UTF8') str=file.read() print(f'str: {str}') file.close() str= str.replace('Python','파이썬',2) print(f'str: {str}') file = open('C:/pythonTxt/about_python.txt','w',encoding='UTF8') file.write(str) file.close()
파일 모드
파일 모드는 파일을 어떤 목적으로 open할지 정한다.'w':쓰기 전용 (파일이 있으면 덮어씌움)
'a':쓰기 전용 (파일이 있으면 덧붙임)
'x':쓰기 전용 (파일이 있으면 에러 발생)
'r':읽기 전용(파일이 없으면 에러 발생)uri = 'C:/pythonTxt/' #w파일 모드 file =open(uri +'hello.txt','w') file.write('Python') file.colse() # #'a'파일 모드 file =open(uri +'hello.txt','a') file.write('\nNice to meet you') file.colse() # #'x'파일 모드 file =open(uri +'hello_01.txt','x') file.write('Nice to meet you') file.colse() # 'r'파일 모드 file =open(uri +'hello_01.txt','r') str=file.read() print(f'str :{str}') file.close()
- with~as문
with~as문을 이용하면 파일 닫기 (close)를 생략할 수 있다.
uri = 'C:/pythonTxt/' #기존 파일 쓰고,읽는 방식 file= open(uri + '5_037.txt','a') file.write('python study!!') file.close() file= open(uri + '5_037.txt','r') print(file.read()) # with~as문을 이용한 방식 with open(uri + '5_037.txt','a') as f: f.write('python study') with open(uri + '5_037.txt','r') as f: print(f.read())
- writelines()
writeliness()는 리스트(List)또는 튜플 데이터(반복 가능 객체)를 파일에 쓰기 위한 함수이다.languages=['c/c++','java','c#','python','javascript'] uri = 'C:/pythonTxt/' with open(uri+'lanuages.txt','a')as f: f.writelines(item + '\n'for item in languages)➜ 반복문 필요없음
- readlines():파일의 모든 데이터를 읽어서 리스트 형태로 반환한다.
- readline():한 행을 읽어서 문자열로 반환 한다.
uri = 'C:/pythonTxt/' with open(uri + 'lans.txt','r') as f: lanList=f.readlines() print(f'lanLisf: {lanList}') with open(uri + 'lans.txt','r') as f: line=f.readline() while line !=' ': print(f'line: {line}') line= f.readline()