Notice
Recent Posts
Recent Comments
Link
«   2025/02   »
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
Archives
Today
Total
관리 메뉴

게임 제작 마스터 클래스

파이썬 수업노트 no. 17 | 파일 읽기, 쓰기 본문

파이썬

파이썬 수업노트 no. 17 | 파일 읽기, 쓰기

엔류 ENRU 2020. 3. 21. 19:26


with open(~, 'w') as f: 에서 에러가 호출되는 경우>> resource 파일이 다른 폴더 안으로 들어가 있는 지 확인하세요.

알고보니 .py파일들을 모두 vscode 파일안에 넣어놨고

이에 따라 resource 파일도 그냥 다른 .py들이 몰려 있는 곳에 넣어놨기 때문이다.

vscode 파일 밖으로 빼놓자 문제는 바로 해결되었다.

# Section09 # 파일 읽기, 쓰기 # 읽기 모드 : r, 쓰기 모드(기존 파일 삭제) : w, 추가모드(파일 생성 또는 추가) : a # .. : 상대경로, . : 절대 경로 # 기타 : https://docs.python.org/3.7/library/function.html#open # 파일 읽기 # 예제1 f = open('./resource/review.txt','r') content = f.read() print(content) print(dir(f)) # 반드시 close 리소스 반환 f.close() print("------------------------------------") print("------------------------------------") # 예제2 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))) # {:6.3} 6자리가 소숫점은 3째자리까지 나와라 # 파일 쓰기 # 예제1 with open('./resource/text1.txt','w') as f: f.write('Niceman!') # 예제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') # 예제3 with open('./resource/text3.txt','w') as f: list = ['Kim\n','Park\n','Cho\n'] f.writelines(list) # 예제4 with open('./resource/text4.txt','w') as f: print('Test Contest1!', file=f) print('Test Contest2!', file=f)



Comments