본문 바로가기

컴퓨터/Python

파일 입출력

파일 객체 = open(file, mode)

file    파일명

mode     r: 읽기모드(디폴트)

w: 쓰기모드

a: 쓰기 + 이어쓰기 모드

+: 읽기 + 쓰기모드

b: 바이너리 모드

t: 텍스트모드(디폴트)

>>> f = open('text.txt','w')

>>> f.write('plow deep\nwhile sluggards sleep')

31

>>> f.close()


바이너리 모드로 mp3 파일 복사하기

>>> f = open('good2.mp3', 'wb')

>>> f.write(open('good.mp3','rb').read())

14412106

>>> f.close()



readline() 한 줄씩 읽음

readlines() 줄 단위로 잘라서 리스트를 반환

seek() 사용자가 원하는 위치로 파일 포인터 이동

tell() 현재 파일에서 어디까지 읽고 썼는지를 나타내는 위치 반환


>>> f = open('text.txt')

>>> f.read()

'plow deep\nwhile sluggards sleep'

>>> f.read()

''

>>> f.tell()

31

>>> f.seek(0)

0

>>> f.read()

'plow deep\nwhile sluggards sleep'

>>> f.seek(0)

0

>>> f.readline()

'plow deep\n'

>>> f.readline()

'while sluggards sleep'

>>> f.readline()

''

>>> f.seek(0)

0

>>> f.readlines()

['plow deep\n', 'while sluggards sleep']

>>> f.readlines()

[]

>>> f.close()



with 구문

close를 특별히 하지 않아도 with 구문을 벗어나면 자동으로 파일이 닫힘

as를 이용해 파일핸들을 명시 함

파일 핸들을 통해 접근 가능

>>> with open('test.txt') as f:

print(f.readline())

print(f.closed)

file write

False

>>> f.closed

True



'컴퓨터 > Python' 카테고리의 다른 글

유닉스 패스워드 크래거  (0) 2013.08.07
pickle  (0) 2013.07.26
포맷팅  (0) 2013.07.26
출력  (0) 2013.07.25
repr(), str(), ascii()  (0) 2013.07.25