파일 다루기_python

Updated:

파일 다루기

파일 열기/닫기

file = open('data.txt')
content = file.read()
file.close()
  • 위와 동일한 코드이지만
    아래와 같이 사용하면 file.close()가 필요없다
with open('data.txt) as file:
  content = file.read()
# file.close() - 필요없음

줄 단위로 읽기

contents = []
with open('data.txt') as file:
  for line in file:
    contents.append(line)

파일의 모드

  • 쓰기 (Write) 모드로 파일을 연다
with open('data.txt', 'w') as file:
  file.write('Hello')
  • default는 read이다

Categories:

Updated:

Leave a comment