본문 바로가기
Algorithm/자료구조, 알고리즘

[코딩 + 알고리즘 완주반] 8일차. 파일 읽기, 쓰기

by newnu 2021. 3. 22.
반응형

# txt 파일 읽기, 쓰기

 

# 파일 읽기

#파일 읽기, 쓰기
# 읽기 모드 : r ,쓰기 모드 (기존 파일 삭제) : w, 추가모드(파일 생성 또는 추가) : a
# .. : 상대경로, . : 절대 경로

# 파일 읽기
# 예제 1
f = open('./resource/review.txt','r')
content = f.read()
print(content)
print(dir(f))
# 반드시 close 리소스 반환
f.close()

print('--------------------------------')
print('--------------------------------')

# 예제2
# with 문을 쓰면 close 안해도 파이썬에서 자동으로 함
with open('./resource/review.txt','r') as f: 
    c = f.read()
    print(c)
    print(list(c))
    print(iter(c))

print('--------------------------------')
print('--------------------------------')

# 예제3
with open('./resource/review.txt','r') as f: 
    for c in f:
        print(c.strip()) # 양쪽 공백 제거

print('--------------------------------')
print('--------------------------------')

# 예제 4
with open('./resource/review.txt','r') as f: 
    content = f.read()
    print('>',content)
    content = f.read() # 내용 없음
    print('>',content)

print('--------------------------------')
print('--------------------------------')

# 예제 5
# 한줄씩 읽기
with open('./resource/review.txt','r') as f: 
    line = f.readline()
    # print(line)
    while line: 
        print(line,end=' #### ')
        line = f.readline()

print('--------------------------------')
print('--------------------------------')

# 예제 6
with open('./resource/review.txt','r') as f: 
    contents = f.readlines() # 리스트로 가져옴
    print(contents)
    for c in contents:
        print(c, end=' ***** ')

print('--------------------------------')
print('--------------------------------')

# 예제 7
score = []
with open('./resource/score.txt', 'r') as f:
    for line in f:
        score.append(int(line))
    print(score)
print('average : {:6.3}'.format(sum(score)/len(score)))

 

# 파일 쓰기

# 파일 쓰기

# 예제 1
with open('./resource/text1.txt','w') as f:
    f.write('Niceman!\n')

 # 예제 2 
 # 기존 파일에 추가
with open('./resource/text1.txt','a') as f:
    f.write('Goodman!\n')   

# 예제 3
from random import randint

with open('./resource/text2.txt','w') as f:
    for cnt in range(6):
        f.write(str(randint(1,50)))
        f.write('\n')

# 예제 4
# writelines : 리스트 -> 파일로 저장
with open('./resource/text3.txt','w') as f:
    list =  ['Kim\n','Park\n','Cho\n']
    f.writelines(list)

# 예제 5
# file 변수 활용
with open('./resource/text4.txt','w') as f:
    print('Test Contests1!', file = f) # 출력하는게 아니고 파일에 쓰기
    print('Test Contests2!', file = f)

 

반응형