질문이 있으십니까?

기본 컨텐츠 및 사용자가 직접 참여하여 만들어진 다양한 내용을 검색합니다.

6.1 파일제어.한줄씩다루기

>>> f = open('C:\\Python27\\readme.txt')
>>> f.readline()
'This is Python version 2.7.1\n'
>>> f.readline()
'============================\n'
>>> f = open('C:\\Python27\\readme.txt')
>>> for x in range(5):
...     line = f.readline()
...     print line,
...
This is Python version 2.7.1
============================

Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
Python Software Foundation.
>>> f = open('C:\\Python27\\readme.txt')
>>> lines = f.readlines()
>>> import sys
>>> sys.stdout.writelines(lines[:5])
This is Python version 2.7.1
============================

Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
Python Software Foundation.
>>> sys.stdout.writelines(lines[15:20])

License information
-------------------

See the file "LICENSE" for information on the history of this
>>>
>>> sys.stdout.writelines(lines[___])
That's all, folks!
------------------


--Guido van Rossum (home page: http://www.python.org/~guido/)
>>>

with문 사용하기

file_data = open("file.txt")
print(file_data.readline(), end="")
file_data.close()
with open("file.txt") as f:
  # 기본적으로 사용하는 함수를 with문 안에 사용하면 되며
  # with문을 나올 때 close를 자동으로 불러줍니다.
  print(f.readline(), end="")

쓰기(Write)

with open("file.txt", "w") as f:
  f.write("First\n")
  f.write("Second")

읽기(Read)

with open("file.txt", "r") as f:
  for line in f:
    print(line)

추가(Append)

with open("file.txt", "a") as f:
  f.write("Third\n")

댓글을 작성하세요

문서 이력

  • 2020-06-07 날짜로 신달수 님으로 부터 컨텐츠명이 변경 되었습니다.
  • 2020-06-09 날짜로 신달수 님께서 등록 작업을 하였습니다.
  • 2020-06-16 날짜로 신달수 님께서 등록 작업을 하였습니다.