Basic/Python
파이썬 - 파일 입출력
HappyWeasel
2019. 4. 9. 12:50
1. 파일 열기 : open(), close() 사용
#파일 객체 = open(파일 이름, 옵션)
f = open("새파일.txt", 'w')
f.close()
- open 옵셥
옵션 | 설명 |
r | 읽기 - 파일을 읽기만 할 때 사용 |
w | 쓰기 - 파일에 내용을 쓸 때 사용 |
a | 추가 - 파일의 마지막에 새로운 내용을 추가 시킬 때 사용 |
* w로 파일에 쓰면 기존의 내용은 삭제 되고 작성한 내용이 저장된다. (덮어씌우기)
- 파일 쓰기 예제
# writedata.py
f = open("C:/doit/새파일.txt", 'w')
for i in range(1, 11):
data = "%d번째 줄입니다.\n" % i
f.write(data)
f.close()
2. 파일 읽기
readline() 함수 : 파일의 첫 번째 줄을 읽어 출력
# readline_test.py
f = open("C:/doit/새파일.txt", 'r')
line = f.readline()
print(line)
f.close()
- 모든 라인을 읽어서 화면에 출력 예제
# readline_all.py
f = open("C:/doit/새파일.txt", 'r')
while True:
line = f.readline()
if not line: break
print(line)
f.close()
readlines() 함수 : 파일의 모든 라인을 읽어서 각각의 줄을 요소로 갖는 리스트로 리턴
f = open("C:/doit/새파일.txt", 'r')
lines = f.readlines()
for line in lines:
print(line)
f.close()
["1 번째 line\n","2 번째 line\n",..., "n 번째 line\n"] -> 이런 형태의 list로 리턴한다.
read() 함수 : 파일의 내용 전체를 문자열로 리턴
f = open("C:/doit/새파일.txt", 'r')
data = f.read()
print(data)
f.close()
3. with 문
기능 : open과 close를 동시에 처리해준다.
* Python 2.5에서부터 지원
with open("foo.txt", "w") as f:
f.write("Life is too short, you need python")
4. sys를 사용하여 입력 받는대로 출력
dos나 console 창에 파일 이름 옆에 인수를 입력하면 바로 출력이 된다.
import sys
args = sys.argv[1:]
for i in args:
print(i)
- 대소문자 변경 예제
import sys
args = sys.argv[1:]
for i in args:
print(i.upper(), end=' ')