윤동주_별헤는밤.txt
0.00MB

 

lena.png

 

※ 파일을 열 때의 위치는 .ipynb와 같은 위치에 있으면 굳이 경로를 설정하지 않아도 되지만,

만약에 같은 위치에 있는 데이터가 아니라면 경로를 전부 써줘야한다.

 

f = open('윤동주_별헤는밤.txt','r',encoding='utf-8')

 

f = open('d:\윤동주_별헤는밤.txt','r',encoding='utf8')

 

 

 

 

1. 텍스트 파일 읽고 출력하기 (read)

1
2
3
4
5
6
7
8
9
10
# 텍스트 파일 읽고 출력하기 (read)
# 파일 불러오고 읽기
file = open('윤동주_별헤는밤.txt','r',encoding='UTF8'# 한글 데이터면 인코딩 필수
 
# 파일 전체 출력
data = file.read()
 
print(data)
 
file.close() # 다 읽고 나면 파일을 닫아주는 것을 
cs

 

 

2. 텍스트 파일 한줄씩 읽고 출력하기 (readline)

1
2
3
4
5
6
7
8
9
10
11
# 텍스트 파일 한 줄 읽고 출력하기 (readline)
= open('윤동주_별헤는밤.txt','r',encoding='UTF8')
poet = f.readline()
 
print(poet) # 별헤는 밤
 
# 시 전문 출력
while poet :
    print(poet,end='')
    poet = f.readline()
f.close()
cs

 

 

3. 사용자로부터 입력받은 내용을 파일로 만들기 (write)

1
2
3
4
5
6
# 사용자로부터 입력받은 내용을 파일로 만들기 (write)
text = input('파일에 저장할 내용을 입력하세요 : ')
 
= open('data.txt','w')
f.write(text)
f.close()
cs

 

 

결과

 

 

4. 텍스트 파일에 한 줄씩 쓰기 (writelines)

1
2
3
4
5
6
7
8
9
10
# 텍스트 파일에 한줄씩 쓰기 (writelines)
listdata = ['a','b','c','d','e','f','g']
 
= open('data2.txt','w')
f.write(str(listdata)) # 문자형으로 반환해서 씀
f.close()
 
= open('data3.txt','w')
f.writelines(listdata)
f.close()
cs

 

 

write하면 리스트 전체가 담김

 

writelines하면 요소가 담김

 

5. 텍스트 파일 복사하기

1
2
3
4
5
6
7
8
9
# 텍스트 파일 복사하기
= open('data3.txt','r')
= open('data3_copy.txt','w')
 
data = f.read()
c.write(data)
 
f.close()
c.close()
cs

 

복사한 결과

 

 

6. 바이너리(이미지,동영상) 파일 복사

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# 이미지 파일 보기
import numpy as np
import PIL.Image as pilimg
import matplotlib.pyplot as plt
 
image = pilimg.open('lena.png')
img = np.array(image)
 
plt.imshow(img)
 
 
# 바이너리 파일 (이미지,동영상) 복사하기
bufsize = 1024
 
= open('lena.png','rb')
= open('lena_copy.png','wb')
 
data = f.read(bufsize)
while data : # 1KB(1024)씩 읽어와서 읽고 쓰고를 반복하는 구조
    c.write(data)
    data = f.read(bufsize)
 
f.close()
c.close()
cs

 

 

 

7. 자동으로 파일 열고 닫기 (with~as)

1
2
3
4
5
6
7
8
9
10
11
# with~as절 사용 x
= open('윤동주_별헤는밤.txt','r',encoding='utf-8')
data = f.read()
print(data)
f.close
 
 
# with~as절 사용 o
with open('윤동주_별헤는밤.txt','r',encoding='utf-8') as f :
    for i in f.readlines() :
        print(i,end='')
cs

 

 

 

+ Recent posts