python 파일 다루기

Garam·2023년 12월 28일
0

왕초보를 위한 Python: 쉽게 풀어 쓴 기초 문법과 실습에서 발췌하였습니다.

python.txt

Programming is fun.
Very fun!

You have to do it yourself...

read

>>> f = open('C:\\python_newbie\\Python_for_Fun.txt')
>>> f.read()
'Programming is fun.\nVery fun!\n\nYou have to do it yourself.'

readline

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

>>> f.readline()
'A. HISTORY OF THE SOFTWARE\n'

>>> f.readline()
'==========================\n'

>>> for x in range(5):
...     f.readline()
...
'\n'
'Python was created in the early 1990s by Guido van Rossum at Stichting\n'
'Mathematisch Centrum (CWI, see http://www.cwi.nl) in the Netherlands\n'
"as a successor of a language called ABC.  Guido remains Python's\n"
'principal author, although it includes many contributions from others.\n'

readlines

파일을 줄마다 원소로 만들어 리스트로 반환함

>>> f = open('LICENSE.txt')
>>> lines = f.readlines()
>>> lines[:2]
['A. HISTORY OF THE SOFTWARE\n', 
'==========================\n']

print를 사용하여 정상적으로 출력하기

>>> buffer = f.read()
>>> print(buffer)
Programming is fun.
Very fun!

You have to do it yourself...

write ('w' 모드: 새로운 파일로 덮어쓰기)

>>> letter = open('C:\\python_newbie\\letter.txt', 'w') # 새 파일 열기
>>> letter.write('Dear Father,')                      # 아버님 전상서
>>> letter.close()                                    # 닫기

write ('a+' 모드: 기존 파일에 데이터 추가하기)

>>> letter = open('C:\\python_newbie\\letter.txt', 'a+')
>>> letter.write('\n\nHow are you?')
>>> letter.close()



0개의 댓글