파이썬 파일 읽기, 쓰기
# 파일 읽기, 쓰기
# 읽기 모드 : r, 쓰기 모드(기존 파일 삭제): w, 추가 모드(파일 생성 또는 추가): a
# 파일 읽기
f = open('./files/review.txt', 'r')
content = f.read()
print(content)
# 반드시 close 리소스 반환
f.close()
print('---------------------')
with open('./files/review.txt','r') as f:
c = f.read()
print(c)
print(list(c))
print(iter(c))
print('--------------------')
with open('./files/review.txt', 'r') as f:
for c in f:
print(c.strip())
print('-----------------')
with open('./files/review.txt', 'r') as f:
content = f.read()
print('>', content)
content = f.read()
print('>', content)
print('-------------------')
with open('./files/review.txt', 'r') as f:
line = f.readline()
# print(line)
while line:
print(line, end='##')
line = f.readline()
with open('./files/review.txt', 'r') as f:
contents = f.readlines()
print(contents)
for c in contents:
print(c, end='###')
score = []
with open('./files/score.txt', 'r') as f:
for line in f:
score.append(int(line))
print(score)
# 6자리 소수점 3번
print('Avg: {:6.3}'.format(sum(score)/len(score)))
with open('./files/text1.txt', 'w') as f:
f.write('Niceman!\n')
with open('./files/text1.txt', 'a') as f:
f.write('Goodman!\n')
from random import randint
with open('./files/text2.txt', 'w') as f:
for cnt in range(6):
f.write(str(randint(1, 50)))
f.write('\n')
with open('./files/text3.txt', 'w') as f:
list = ['kim\n', 'park\n', 'lee\n']
f.writelines(list)
with open('./files/text4.txt', 'w') as f:
print('Test Contests1', file=f)
print('Test Contests2', file=f)