파이썬 기본 _ 입출력 : 함수, 입출력, 파일읽기쓰기
파이썬
입출력
1. 함수
1) 기본 구조
def 함수_이름(매개변수):
수행할_문장1
수행할_문장2
...
def add(a, b):
return a + b
pirnt(add(1, 2)
>>> 3
: a와 b는 매개변수/인자, 1과 2는 인수
2. 파일 읽기 / 쓰기
파일_객체 = open(파일_이름, 파일_열기_모드)
1) 쓰기 : 'w'
f = open("새파일.txt", 'w')
f.close()
f = open("C:/doit/경로/새파일.txt", 'w')
f.close()
f = open("C:/doit/새파일.txt", 'w')
for i in range(1, 11):
data = "%d번째 줄입니다.\n" % i
f.write(data)
f.close()
2) 읽기 : 'r'
f = open("C:/doit/새파일.txt", 'r')
line = f.readline()
print(line)
f.close()
>>> 1번째 줄입니다.
f = open("C:/doit/새파일.txt", 'r')
while True:
line = f.readline()
if not line:
break
print(line)
f.close()
: .readline() 첫째줄만 읽기
f = open("C:/doit/새파일.txt", 'r')
lines = f.readlines()
for line in lines:
print(line)
f.close()
f = open("C:/doit/새파일.txt", 'r')
data = f.read()
print(data)
f.close()
3) for문과 읽기
f = open("C:/doit/새파일.txt", 'r')
for line in f:
print(line)
f.close()
4) 내용 추가 : 'a'
f = open("C:/doit/새파일.txt",'a')
for i in range(11, 20):
data = "%d번째 줄입니다.\n" % i
f.write(data)
f.close()
: 'w'는 새 파일이 생기면서 데이터를 새로 쓰는 것, 따라서 같은 이름의 파일이 있다면 삭제되고 새 데이터가 쓰임.
그러나 'a'는 기존 데이터 뒤에 이어서 씀.
5) with로 읽기
with open("foo.txt", "w") as f:
f.write("Life is too short, you need python")