# 파이썬 파일 다루기

- Author: @wolfsil
- Published: 2023-10-06
- Updated: 2023-10-17
- Source: http://blex.me/@wolfsil/2023-10-6-%EC%98%A4%ED%9B%84-31725
- Tags: python

---

# 파이썬 파일 다루기

```jsx
#방법 쓰기 1
file = open('hello.txt', 'w')
file.write('Hello, world!')
file.close()

#방법 쓰기 2
with open('hello.txt', 'w') as file:    
	file.write("안녕")

#방법 한번에 많이 쓰기
with open('hello.txt', 'w') as file:    
	file.writelines(['안녕하세요.\n', '파이썬\n', '코딩 도장입니다.\n'])

#방법 읽기 줄을 나눠서 읽기
with open('hello.txt', 'r') as file: 
    lines = file.readlines() #배열 반환
    print(lines)

#방법 읽기 모두 한번에 읽기
with open('hello.txt', 'r') as file: 
    line = file.read()
    print(line)

#방법 추가하기 
with open('hello.txt', 'a+') as file: 
    print(file.read())#커서가 맨 뒤. 공백 출력
    file.write("끝")
```

- 쓰기 모드로 열면 적혀 있던 내용 모두 삭제된다.(+를 붙이던 말던)
- +를 붙이면 읽고 쓸수 있게된다.(w는 어차피 삭제되므로 의미 없다)
- w r로 시작하면 포인터가 맨 앞에서, a로 시작하면 뒤에서 시작한다
- wb, ab, rb 등 바이너리를 저장하는 방법도 있다.
