Coding & Programming/Python 기초(A-Z)

[Python:파이썬:기초] 15. 파일 생성, 읽기, 쓰기, 파일 복사(Create/Read/Write/Copy Files)

mainCodes 2021. 5. 24. 09:35

[Python:파이썬:기초] 15. 파일 생성, 읽기, 쓰기, 파일 복사(Create/Read/Write/Copy Files)

 

안녕하세요 JollyTree입니다 (•̀ᴗ•́)و

 

파이썬은 open 함수를 이용하여 파일을 읽거나 파일을 새로 생성해요.  open 함수는 두 개의 파라미터를 가지는데 첫 번째는 파일명이고 두 번째는 파일을 열기 위한 모드(mode)로 모드는 상황에 맞게 파일을 open 할 수 있어요. 다음은 open함수의 이용 예입니다.

 

open 함수 사용 예

 

f1 = open("c:/temp/maincodes1.txt", "r")

f1 = open("c:/temp/maincodes3.zip", "rb")

f2 = open("c:/temp/maincodes4.txt", "w")

f2 = open("c:/temp/maincodes3.txt", "a")

 

open 모드(mode)
모드 설명
r 읽기 모드 - 파일을 읽기 모드로 Open
w 쓰기 모드 - 파일을 쓰기 모드로 Open
t 텍스트 모드 - 파일을 텍스트 모드로 Open(디폴트 값임)
b 바이너리 모드 - 파일을 바이너리 모드로 Open
x 확인 모드 - 파일이 생성시 존재 여부 확인 모드로 Open
a 추가 모드 - 파일의 마지막에 새로운 내용을 추가하는 모드로 Open

 

만약, 바이너리(이진)파일을 "r" 모드로 열고자 하면 다음과 같은 에러가 발생하니 "rb"와 같이 2개 모드를 조합여 open을 해야 합니다. 그리고 "x" 확인 모드로 열었는데 이미 파일이 존재하면 파이썬은 아래와 같은 에러를 발생시킵니다.

 

FileExistsError: [Errno 17] File exists: 

 

"r" 읽기모드로 파일을 열었는데 파일이 없는 경우도 아래와 같은 에러가 발생합니다.

 

FileNotFoundError: [Errno 2] No such file or directory: 

 

예제는 텍스트/바이너리 파일 읽기와 생성, 파일 복사 등 파이썬 언어를 이용한 여러 가지 파일 핸들링 방법을 보여줍니다. 

파일 생성, 읽기, 쓰기, 파일 복사 예제(Example):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#텍스파일 읽기
f1 = open("c:/temp/maincodes1.txt""r")
f1_data = f1.read()
f1.close()
 
#텍스파일 쓰기
f2 = open("c:/temp/maincodes2.txt""w")
len = f2.write(f1_data)
print("maincodes2.txt: 총 %d 바이트 크기의 파일을 생성하였습니다." % len)
f2.close()
 
#바이너리(이진) 파일 읽기
f1 = open("c:/temp/maincodes3.zip""rb")
f1_data = f1.read()
f1.close()
 
#바이너리(이진) 파일 쓰기
f2 = open("c:/temp/maincodes4.zip""wb")
len = f2.write(f1_data)
print("maincodes4.zip: 총 %d 바이트 크기의 파일을 생성하였습니다." % len)
f2.close()
 
#텍스트 파일 라인단위로 읽고 쓰기(readline 함수)
f1 = open("c:/temp/maincodes1.txt""r")
f2 = open("c:/temp/maincodes3.txt""w")
sum = 0
while True:
    f1_data = f1.readline()
    if not f1_data:
        break
    len = f2.write(f1_data)
    sum += len
 
f1.close()
f2.close()
    
#텍스트 파일 라인단위로 읽고 쓰기(readlines 함수)
f1 = open("c:/temp/maincodes1.txt""r")
f2 = open("c:/temp/maincodes4.txt""w")
f1_data_list = f1.readlines() #읽어서 리스트로 리턴
sum = 0
for line in f1_data_list:
    len = f2.write(line)  #리스트 요소 쓰기
    sum += len    
        
print("maincodes4.txt: 총 %d 바이트 크기의 파일을 생성하였습니다." % sum)    
f1.close()
f2.close()
 
#a 모드 : 이미 생성된 maincodes3.txt에 내용을 추가
f1 = open("c:/temp/maincodes1.txt""r")
f2 = open("c:/temp/maincodes3.txt""a")
sum = 0
while True:
    f1_data = f1.readline()
    if not f1_data:
        break
    len = f2.write(f1_data)
    sum += len
    
print("maincodes3.txt: 총 %d 바이트 크기의 파일을 생성하였습니다." % sum)    
f1.close()
f2.close()
 
cs

 

예제를 에러 없이 실행하기 위해서는 maincodes1.txt와 maincodes3.zip 파일이 c:\temp 폴더에 있어야 합니다. 아래 그림은 maincodes1.txt 파일 내용입니다.  그리고 예제에서 사용하는 maincodes3.zip은 maincodes1.txt 파일을 압축한 파일입니다. 

 

실행결과(Output):

실행 후 c:\temp 폴더에는 다음과 같이 maincodes2.txt, maincodes4.zip, maincodes4.txt, maincodes3.txt이 생성된 것을 확인할 수 있으며 .txt 파일들은 텍스트 에디터로 열어보면 각 모드에 맞게 파일 내용이 생성된 것을 볼 수 있습니다. .zip 파일은 압축을 해제한 후 .txt 파일을 텍스트 에디터로 확인할 수 있습니다.

 

이상 JollyTree였습니다 (•̀ᴗ•́)و