파일 읽기 및 쓰기

 

 

 

 

 

읽기 모드 : r, 쓰기모드 w, 추가 모드 a(append), 텍스트 모드(기본값,생략가능) t, 바이너리 모드 b
상대 경로('../<상위폴더>, ./<현재폴더>'), 절대 경로('C:\Django\example..')

##파일 Write 실습(1)
'''
open함수 설명
Mode 설명
다양한 읽기(read) 방법
다양한 쓰기(write) 방법
입출력 중요 설명
'''

 

 

 

주의!

import os

print(os.getcwd())가 자신이 작업하고 있는 폴더를 정확히 가리키고 있는지 확인해야한다!

만약 그렇지 않으면 상대경로가 파일을 찾지 못한다!

 

C:\Users\Jaesang Choi\Desktop\python_basic

 

 

 


# 파일 읽기(Read)

 


# 예제1

f = open('./resource/it_news.txt', 'r', encoding='UTF-8') #rt라고 해도 된다. t는 기본값이라 빼도 됨

# 속성 확인
print(dir(f)) #['_CHUNK_SIZE', '__class__', '__del__', '__delattr__', '__dict__', '__dir__'...]

# 인코딩 확인
print(f.encoding) #UTF-8

# 파일 이름
print(f.name) #./resource/it_news.txt

# 모드 확인
print(f.mode) #r
cts = f.read()
print(cts)

Right now gamers can pay just $1 for access to hundreds of titles across PC 
and Xbox via Microsoft Xbox Game Pass Ultimate service?but dont 
activate that insanely cheap one-month trial just yet. You can lock in up to 
three years of Xbox Game Pass Ultimate with that same dollar if you play 
your cards right.

When you activate Microsoft��s E3 2019 promotion, it not only begins the trial, 
but also converts existing Xbox Live Gold and standard Xbox Game Pass 
subscriptions on your account to Game Pass Ultimate (normally $15 per 
month). Any prepaid time up to the maximum of three years gets the upgrade.


# 사용한 후에는 반드시 close!
f.close()

 



# 예제2

with open('./resource/it_news.txt', 'r', encoding='UTF-8') as f:
    c = f.read()
    print(c)
    
Right now gamers can pay just $1 for access to hundreds of titles across PC 
and Xbox via Microsoft Xbox Game Pass Ultimate service?but dont 
activate that insanely cheap one-month trial just yet. You can lock in up to 
three years of Xbox Game Pass Ultimate with that same dollar if you play 
your cards right.

When you activate Microsoft��s E3 2019 promotion, it not only begins the trial, 
but also converts existing Xbox Live Gold and standard Xbox Game Pass 
subscriptions on your account to Game Pass Ultimate (normally $15 per 
month). Any prepaid time up to the maximum of three years gets the upgrade.

    print(iter(c)) #<str_iterator object at 0x7fa21c6c8ac0> 이런게 나왔다면 for문이나 반복문같은 곳에서 사용할 수 있다는 것


    print(list(c)) #['R', 'i', 'g', 'h', 't', ' ', 'n', 'o', 'w', ' ', 'g', 'a', 'm'...]
    
 #with문에서는 사용한 후에 close를 호출하지 않아도 내부적으로 리소스가 닫힌다.

 



# 예제3

# read() : 전체 읽기 , read(10) : 10Byte만큼 읽어 옴

with open('./resource/it_news.txt', 'r', encoding='UTF-8') as f:
    c = f.read(20)
    print(c)
    c = f.read(20) #커서가 내부적으로 동작을 해서 내가 마지막에 어디까지 읽었는지를 내부적으로 기억하고 있다.
    print(c)
    c = f.read(20)
    print(c)
    f.seek(0,0) #나는 (0,0)으로 이동하고 다시 읽겠다.
    c = f.read(20)
    print(c)
    
    
    
Right now gamers can
 pay just $1 for acc
ess to hundreds of t
Right now gamers can





# 예제4

# readline : 한 줄 씩 읽기

with open('./resource/it_news.txt', 'r', encoding='UTF-8') as f:
    line = f.readline() #끝에 \n 줄바꿈이 온다.
    print(line)
    line = f.readline()
    print(line)



Right now gamers can pay just $1 for access to hundreds of titles across PC 

and Xbox via Microsoft Xbox Game Pass Ultimate service?but dont 
#\n줄바꿈에 print()자동 줄바꿈이 만나서 한 줄이 띄어진다.






# 예제5

# readlines : 전체를 읽은 후 라인 단위 리스트로 저장

with open('./resource/it_news.txt', 'r', encoding='UTF-8') as f:
    cts = f.readlines()
    print(cts) #['Right now gamers can pay just $1 for access to hundreds of titles across PC \n', 'and Xbox via Microsoft Xbox Game Pass Ultimate service?but dont \n', ...]
    print()
    for c in cts:
        print(c, end='') #end=''로 print의 자동 줄바꿈을 없앴다.
        
Right now gamers can pay just $1 for access to hundreds of titles across PC 
and Xbox via Microsoft Xbox Game Pass Ultimate service?but dont 
activate that insanely cheap one-month trial just yet. You can lock in up to 
three years of Xbox Game Pass Ultimate with that same dollar if you play 
your cards right.

When you activate Microsoft��s E3 2019 promotion, it not only begins the trial, 
but also converts existing Xbox Live Gold and standard Xbox Game Pass 
subscriptions on your account to Game Pass Ultimate (normally $15 per 
month). Any prepaid time up to the maximum of three years gets the upgrade.





# 파일 쓰기(write) 기존에 있는 파일을 연결할 때도 오픈을 썼다면 우리가 쓰고자하는 없는 파일을 가상으로
                         연결을 할 때도 open함수를 쓴다.

 


# 예제1

with open('./resource/contents1.txt', 'w') as f:
    f.write('I love python\n')

 

contents1.txt

 

I love python

 

 



# 예제2(추가)

with open('./resource/contents1.txt', 'a') as f:
    f.write('I love python2\n')
    #w를 쓰면 기존의 내용 I love python이 없어지고 I love python2가 덮어씌어진다.

 

contents1.txt

 

I love python
I love python2




# 예제3

# writelines : 리스트 -> 파일
with open('./resource/contents2.txt', 'w') as f:
    list = ['Orange\n', 'Apple\n', 'Banana\n', 'Melon\n']
    f.writelines(list)

 

contents2.txt

Orange
Apple
Banana
Melon

 

 

 



# 예제4

with open('./resource/contents3.txt', 'w') as f:
    print('Test Text Write!', file=f)
    print('Test Text Write!', file=f)
    print('Test Text Write!', file=f)
    
#콘솔에 출력되지 않고 contents3파일로 출력을 해준다.

 

contents3.txt

Test Text Write!
Test Text Write!
Test Text Write!

 

 

 

 

 

'Python > Today I learned' 카테고리의 다른 글

TIL#34 클래스 self  (0) 2021.05.20
TIL#33 CSV 파일 읽기 및쓰기  (0) 2021.05.19
TIL#31 외장함수  (0) 2021.05.19
TIL#30 내장함수  (0) 2021.05.19
TIL#29 예외(exception)  (0) 2021.05.19

+ Recent posts