-
File ObjectsPython 2020. 8. 22. 13:52
with open('path_to_file', 'r') as f: # Do something with f
위 사용법 이외의 사용법외의 다른 유용한 method, attribute를 찾아봤다
1-1. 파일 내용 가져오기: read()
with open('test.txt', 'r') as f: f_contents = f.read() print(f_contents)
1-2. 글자수만큼 가져오기: read(num_characters)
with open('test.txt', 'r') as f: size_to_read = 10 f_contents = f.read(size_to_read) print(f_contents)
1-3. 파일 시작 지점으로 돌아오기: seek(0)
with open('test.txt', 'r') as f: a = f.read(10) b = f.read(10) f.seek(0) c = f.read(10) print(a) print(b) print(c)
2-1. 라인별로 가져오기 (전체): readlines()
with open('test.txt', 'r') as f: f_contents = f.readlines() print(f_contents)
2-2. 라인별로 가져오기 (한줄씩): readline()
with open('test.txt', 'r') as f: f_contents = f.readline() print(f_contents)
2-3. 라인별로 가져오기 (Iterator 이용)
with open('test.txt', 'r') as f: for line in f: print(line)
3-1. 파일 쓰기: write()
with open('test.txt', 'w') as f: f.write('TEST')
3-2. 파일 쓰기: binary
with open('input.jpg', 'rb') as if: with open('output.jpg', 'wb') as of: of.write(if.read())
References:
Python Tutorial: FIle Objects - Reading and Writing to Files
'Python' 카테고리의 다른 글
argparse 모듈로 커맨드라인 인자 가져오기 (0) 2020.05.28 (A,) <-- 콤마는 왜쓰는걸까? (1D Tuple) (0) 2020.05.23 super() (0) 2020.05.22