OPEN 함수 및 기능
open 함수 사용법
- 객체 = open(파일명,모드,encoding=='utf-8')
- 객체.close()
파일 생성
- file = open('new.txt','w')
- file.close()
파일 객체 = open(파일이름, 파일 열기 모드)
-file = open("./hello.txt",'w')
-file.close
<파일 열기 모드>
'r' = 읽기 모드로 연다
'w' = 쓰기 모드로 연다(기존내용 삭제)
'a' = 쓰기 모드로 연다(기존내용 보존)
'b' = 이진 모드로 연다
't' = 텍스트 모드로 연다
pwd
출력: 현재 경로가 나온다.
file = open('sample1.txt','w',encoding='utf-8')
file.write('안녕하세요. 반갑습니다.')
file.close() #저장
file = open('sample2.txt','w',encoding='utf-8')
file.write('----'*20 + '\n')
for i in range(1,4):
sentence = f'{i}번 항목. \n'
file.write(sentence)
file.write('----'*20)
file.close()
# readline 파일에서 한 줄을 읽어 출력
f =open('sample2.txt','r',encoding='utf-8')
line1 = f.readline()
print(line1)
f =open('./sample2.txt',encoding='utf-8')
while True:
b = f.readline()
if not b: #b가 없다면
break # 멈추고
print(b) #아니면 그냥 출력 해라.
f.close()
#ReadLines
#readlines()
모든 줄을 읽고 각 줄을 요소로 갖는 리스트 반환
f = open('sample2.txt','r')
a=f.readlines()
print(a)
for i in a:
print(i)
f.close()
#read()
# 파일 내용 전체를 문자열로 반환
f = open('sample2.txt','r')w
a=f.read()
print(a)
f.close
구구단 3단 저장 후 읽기 !
#구구단 3단 저장 후 읽기
file = open('googoo.txt','w',encoding='utf-8')
print('-' * 50)
for i in range(3,4):
for a in range(1,10):
googoo3 =(f'{i}x{a}={i*a}\n')
file.write(googoo3)
file.close()
readline을 활용해서 실행 결과 출력
#readline 활용 실행 결과가 나오게 출력해보세요.
file = open('googoo.txt','r',encoding='utf-8')
while True:
a = file.readline() # 변수 지정
if not a: #내용이 없다면
break # 멈추고
print(a) #아니면 그냥 출력 해라.
file.close()
print('출력끝')
출력:
3x1=3
3x2=6
3x3=9
3x4=12
3x5=15
3x6=18
3x7=21
3x8=24
3x9=27
출력끝
With open(파일명,모드)as 변수:
Withopen을 사용 하면 file.close를 하지 않아도 저장이 된다.
줄이 짧아지는 장점이 있다 !
with open('write.txt','w')as a:
a.write('Welcome to Python')
'Python' 카테고리의 다른 글
Python - Numpy (1) | 2022.09.21 |
---|---|
Python 초급 - csv 파일 원하는 부분 불러오기 (0) | 2022.09.01 |
Python 기초 - 함수 (0) | 2022.08.31 |
python 초급 - dict 와 for문 이용 (0) | 2022.08.29 |
Python 기초 - While문, 분기문 (0) | 2022.08.29 |