파일과 관련된 기본적인 메소드
os.getcwd() | 파일 위치를 가져온다 |
open() | 해당파일을 열어준다. mode, encoding 등의 설정을 수정할 수 있다. |
read() | 파일을 읽어준다. |
close() | 파일을 닫아준다. 파일을 열었으면 닫아주는게 정석이다. |
mode의 종류
문자 | 의미 |
'r' | 읽기 모드 (기본값) |
'w' | 쓰기 모드 |
'a' | 파일을 쓰기용으로 열되, 파일의 내용 끝에 데이터를 추가할때 사용 |
'b' | 바이너리 모드 |
't' | 텍스트 모드 |
'+' | 갱신 모드 |
코드 전체보기
# file i/o
import os
print(os.getcwd())
try:
print('읽기 ---')
# f1 = open(r'c:\work\psou\pro1\pack3\file_test.txt',mode='r',encoding='utf8')
# f1 = open(os.getcwd() + '\\file_test.txt', mode='r', encoding='utf8')
f1 = open('file_test.txt', mode='r', encoding='utf8') # mode= 'r','w','a','b'....
print(f1)
print(f1.read())
f1.close()
print('저장 ---')
f2 = open('file_test2.txt', mode='w', encoding='utf8')
f2.write('My friends\n')
f2.write('홍길동, 나길동')
f2.close()
print('추가 ---')
f3 = open('file_test2.txt', mode='a', encoding='utf8')
f3.write('\n손오공')
f3.write('\n팔계')
f3.write('\n오정')
f3.close()
print('읽기---')
f4 = open('file_test2.txt', mode='r', encoding='utf8')
print(f4.readline())
print(f4.readline())
except Exception as e:
print('에러 :',e)
C:\work\psou\pro1\pack3
읽기 ---
<_io.TextIOWrapper name='file_test.txt' mode='r' encoding='utf8'>
가을이 깊어지고
파이썬도 깊어가고
DB연동
프로그램이
서서히 다가오고 있다
저장 ---
추가 ---
읽기---
My friends
홍길동, 나길동
파일을 불러오는 기본적인 형태
# file i/o
import os
print(os.getcwd())
try:
print('읽기 ---')
# f1 = open(r'c:\work\psou\pro1\pack3\file_test.txt',mode='r',encoding='utf8')
# f1 = open(os.getcwd() + '\\file_test.txt', mode='r', encoding='utf8')
f1 = open('file_test.txt', mode='r', encoding='utf8') # mode= 'r','w','a','b'....
print(f1)
print(f1.read())
f1.close()
except Exception as e:
print('에러 :',e)
C:\work\psou\pro1\pack3
읽기 ---
<_io.TextIOWrapper name='c:\\work\\psou\\pro1\\pack3\\file_test.txt' mode='r' encoding='utf8'>
가을이 깊어지고
파이썬도 깊어가고
DB연동
프로그램이
서서히 다가오고 있다
파일을 불러오는 3가지 형태
마지막 줄은 같은 패키지에 있기 때문에 가능하다.
f1 = open(r'c:\work\psou\pro1\pack3\file_test.txt',mode='r',encoding='utf8')
f1 = open(os.getcwd() + '\\file_test.txt', mode='r', encoding='utf8')
f1 = open('file_test.txt', mode='r', encoding='utf8')
파일 작성하여 저장하기
새로운 파일이 생성된다
print('저장 ---')
f2 = open('file_test2.txt', mode='w', encoding='utf8')
f2.write('My friends\n')
f2.write('홍길동, 나길동')
f2.close()
파일 추가하기
기존파일에 추가된다
print('추가 ---')
f3 = open('file_test2.txt', mode='a', encoding='utf8')
f3.write('\n손오공')
f3.write('\n팔계')
f3.write('\n오정')
f3.close()
한줄씩 읽기
readline()
print('읽기---')
f4 = open('file_test2.txt', mode='r', encoding='utf8')
print(f4.readline())
print(f4.readline())
'python' 카테고리의 다른 글
file - 파일에서 특정 단어를 포함하는 줄만 출력(주소 출력기) (1) | 2022.10.11 |
---|---|
file - file + with, pickle (0) | 2022.10.11 |
예외처리 - try ~ except (0) | 2022.10.11 |
class - 추상 클래스 예제 (0) | 2022.10.11 |
class - 추상클래스 (0) | 2022.10.11 |