[플레이데이터]
[PlayData - Day 4] 입력과 출력
EYZ27
2022. 12. 22. 16:13
1. K-Digital Training 과정
- 빅데이터 기반 지능형SW 및 MLOps 개발자 양성과정 19기 (Day 4)
2. 목차
- 화면 출력과 formatting
- 키보드 입력받기: input()
- 파일 읽고 쓰기
- 반복문을 이용해 파일 읽고 쓰기
- with문을 활용해 파일 읽고 쓰기
3. 수업 내용
1. 화면 출력와 formatting
- print 함수의 사용
print("hello python")
> hello python
print("Best","python","book")
> Best python book
print("Best","python","book", sep="-:*:-")
> Best-:*:-python-:*:-book
# 빈칸없이 문자를 연결할 때 + 사용
print("abcf"+"efg")
> abcfefg
# 콤마와 + 같이 사용하면?
print("Best","python","book" + ":", "This book")
> Best python book: This book
# 변수에 저장된 내용을 출력할 때
x = 10
print(x)
> 10
# 문자열과 숫자를 함께 출력
name = "James"
ID_num = 789
print("Name:", name + ",", "ID Number:", ID_num)
> Name: James, ID Number: 789
# 여러줄로 출력하기 (개행문자 \n)
print("James is my friend.\nHe is Korean.")
> James is my friend.
> He is Korean.
# 줄을 바꾸지 않고 출력
print("Welcome to ")
print("python!")
> Welcome to
> python!
# 두 줄로 출력된 결과를 한 줄로 출력하기 (end 사용)
print("Welcome to ", end="")
print("python!")
> Welcome to python!
name = "광재"
print("%s는 나의 친구입니다." %name)
> 광재는 나의 친구입니다.
r = 3
PI = 3.14159265358979
print("반지름: %d, 원주율: %f" % (r, PI))
# 지정된 위치에 데이터 출력
> 반지름: 3, 원주율: 3.141593
- 형식 지정 위치에서 출력
- string.format을 이용하는 형식지정 문자열의 기본 구조 print("{0},{1},{2}...{n}" format(data_0, data_!, data_2, ..., data_n)
animal_0 = "cat"
animal_1 = "dog"
animal_2 = "fox"
print("Animal: {0}".format(animal_0))
print("Animal: {0},{1},{2}".format(animal_0,animal_1,animal_2))
> Animal: cat
> Animal: cat,dog,fox
# 일부만 출력해도 되고, 비워둬도 된다
print("Animal: {0},{2}".format(animal_0,animal_1,animal_2))
print("Animal: {},{},{}".format(animal_0,animal_1,animal_2)) # 순서대로 출력됨
> Animal: cat,fox
> Animal: cat,dog,fox
# 정수나 실수도 출력가능
# 문자열을 변수에 대입한 후 변수를 불러서 출력
# 실수의 경우 17자리까지 표현되며, 반올림되어 출력된다.
name = "Tomas"
age = 10
a = 0.1234567890123456798
fmd_string = "String: {0}, Integer Number: {1}, Floating Number: {2}"
print(fmd_string.format(name,age,a))
> String: Tomas, Integer Number: 10, Floating Number: 0.12345678901234568
- 형식 지정 문자열에서 숫자 출력 형식 지정
# 데이터가 숫자일 경우 {N:'출력형식'}을 지정하여 다양한 형태로 출력이 가능
print("{0:.2f}, {0:6.5f}".format(a))
# . 앞의 자리는 전체 공간, . 뒤의 자리는 소수점 어디까지 보여줄지 정하는 숫자
> 0.12, 0.12346
2. 키보드 입력
# data = input("문자열")
yourName = input("당신의 이름은? ")
print("당신은 {}이군요.".format(yourName))
> 당신의 이름은? eyz
> 당신은 eyz이군요.
# 숫자를 입력한 예
num = input("숫자를 입력하세요. ")
print("당신이 입력한 숫자는 {}입니다.".format(num))
> 숫자를 입력하세요. 10
> 당신이 입력한 숫자는 10입니다.
# 숫자를 연산에 이용하기 위해서는 변환해야한다
a = input("정사각형 한 변의 길이는? ")
area = int(a)**2
print("정사각형의 넓이: {}".format(area))
> 정사각형 한 변의 길이는? 5
> 정사각형의 넓이: 25
# 실수의 경우(정수인지 실수인지 모르는 경우 실수로 하는 것이 좋음)
a = input("정사각형 한 변의 길이는? ")
area = float(a)**2
print("정사각형의 넓이: {}".format(area))
> 정사각형 한 변의 길이는? 5
> 정사각형의 넓이: 25.0
3. 파일 읽고 쓰기
- 출력 결과를 화면이 아니라 파일로 출력하거나 읽어야할 경우
- 파일 열기
- 내장 함수인 open()을 이용해 파일을 열어야 한다.
f = open('file_name','mode')
<mode 종류>
r : 읽기 모드로 파일 열기(기본). 모드를 지정하지 않으면 기본적으로 읽기 모드로 지정됨.
w : 쓰기 모드로 파일 열기. 같은 이름의 파일이 있으면 기존 내용은 모두 삭제됨.
x : 쓰기 모드로 파일 열기. 같은 이름의 파일이 있을 경우 오류가 발생함.
a : 추가 모드로 파일 열기. 같은 이름의 파일이 없으면 w와 기능 같음.
------------------------------------------------------------------------------------------------------------------------
b : 바이너리 파일 모드로 파일 열기.
t : 텍스트 파일 모드로 파일 열기(기본). 지정하지 않으면 기본적으로 텍스트 모드로 지정됨.
혼합 사용 가능:
'rt' 읽기 모드 + 텍스트 모드
'bw' 혹은 'wb' 바이너리 파일을 읽기 모드로 열기
- 내장 함수인 open()을 이용해 파일을 열어야 한다.
- 파일 쓰기
- f = open('file_name','w')
f.write(str)
f.close
- f = open('file_name','w')
## 폴더로 이동하기 명령
cd C:\myPyCode
> C:\myPyCode
## 파일을 쓰기 모드로 열고, 문자열 입력 후 파일 닫기 코드
f = open('myFile.txt', 'w') # (1) 'myFile.txt' 파일 쓰기 모드로 열기
f.write('This is my first file.') # (2) 연 파일에 문자열 쓰기
f.close() # (3) 파일 닫기
## 파일 이름을 이용하여 내용 확인하기
!type myFile.txt
> This is my first file.
- 파일 읽기
f = open('myFile.txt', 'r') # (1) 'myFile.txt' 파일 읽기 모드로 열기
file_text = f.read() # (2) 파일 내용 읽은 후에 변수에 저장
f.close() # (3) 파일 닫기
print(file_text) # 변수에 저장된 내용 출력
> This is my first file.
4. 반복문을 이용해 파일 읽고 쓰기
- 파일에 문자열 한 줄씩 쓰기
f = open('two_times_table.txt','w') # (1) 파일을 쓰기 모드로 열기
for num in range(1,6): # (2) for문: num이 1~5까지 반복
format_string = "2 x {0} = {1}\n".format(num, 2*num) # (3) 저장할 문자열 생성
f.write(format_string) # (4) 파일에 문자열 저장
f.close() # (5) 파일 닫기
!type two_times_table.txt
> 2 x 1 = 2
> 2 x 2 = 4
> 2 x 3 = 6
> 2 x 4 = 8
> 2 x 5 = 10
- 파일에 문자열 한 줄씩 읽기
- readline()
f = open("two_times_table.txt") # 파일을 읽기모드(기본값)로 열기
line1 = f.readline() # 한 줄씩 문자열을 읽기
line2 = f.readline()
f.close() # 파일 닫기
print(line1, end='') # 한 줄씩 문자열 출력(줄바꿈 안함...을 해도 줄바꿔지네?)
print(line2, end='')
> 2 x 1 = 2
> 2 x 2 = 4
# while문을 활용한 출력
f = open("two_times_table.txt") # 파일을 읽기모드(기본값)로 열기
line = f.readline() # 한 줄씩 문자열을 읽기
while line: # line이 공백인지 검사해서 반복 여부 결정
print(line, end = '') # 문자열 한 줄 출력(줄 바꿈 안함)
line = f.readline() # 문자열 한 줄 읽기
f.close() # 파일 닫기
> 2 x 1 = 2
> 2 x 2 = 4
> 2 x 3 = 6
> 2 x 4 = 8
> 2 x 5 = 10
- readlines()
# 한꺼번에 읽기가 가능하다
f = open("two_times_table.txt") # 파일을 읽기모드(기본값)로 열기
lines = f.readlines() # 한 줄씩 문자열을 읽기
f.close() # 파일 닫기
print(lines)
> ['2 x 1 = 2\n', '2 x 2 = 4\n', '2 x 3 = 6\n', '2 x 4 = 8\n', '2 x 5 = 10\n']
# for문을 이용하여 전체 읽기
f = open("two_times_table.txt") # 파일을 읽기모드(기본값)로 열기
lines = f.readlines() # 한 줄씩 문자열을 읽기
f.close() # 파일 닫기
for line in lines: # 리스트를 <반복 범위>로 지정
print(line, end='') # 리스트 항목을 출력(줄바꿈 안함)
> 2 x 1 = 2
> 2 x 2 = 4
> 2 x 3 = 6
> 2 x 4 = 8
> 2 x 5 = 10
f = open("two_times_table.txt") # 파일을 읽기모드(기본값)로 열기
for line in f.readlines(): # 파일 전체를 읽고, 리스트 항목을 line에 할당
print(line, end='') # 리스트 항목을 출력(줄바꿈 안함)
f.close() # 파일 닫기
> 2 x 1 = 2
> 2 x 2 = 4
> 2 x 3 = 6
> 2 x 4 = 8
> 2 x 5 = 10
f = open("two_times_table.txt") # 파일을 읽기모드(기본값)로 열기
for line in f: # 파일 전체를 읽고, 리스트 항목을 line에 할당
print(line, end='') # 리스트 항목을 출력(줄바꿈 안함)
f.close() # 파일 닫기
> 2 x 1 = 2
> 2 x 2 = 4
> 2 x 3 = 6
> 2 x 4 = 8
> 2 x 5 = 10
5. with문을 활용해 파일 읽고 쓰기
- with문의 구조
- with open('file_name','mode') as f:
<코드블록>
- with open('file_name','mode') as f:
f = open('myTextFile.txt','w') # 파일 열기
- with문의 활용
with open('C:/myPyCode/myTextFile2.txt', 'w') as f: # (1) 파일 열기
f.write('File read/write text2: line1\n') # (2) 파일 쓰기
f.write('File read/write text2: line2\n')
f.write('File read/write text2: line3\n')
with open('C:/myPyCode/myTextFile2.txt') as f: # (!) 파일 열기
file_string = f.read() # (2) 파일 읽기
print(file_string)
> File read/write text2: line1
> File read/write text2: line2
> File read/write text2: line3
with open('C:/myPyCode/myTextFile3','w') as f:
for num in range(1,6):
format_string = '3 x {0} = {1}\n'.format(num, num*3)
f.write(format_string)
with open('C:/myPyCode/myTextFile3', 'r') as f:
for line in f:
print(line, end='')
> 3 x 1 = 3
> 3 x 2 = 6
> 3 x 3 = 9
> 3 x 4 = 12
> 3 x 5 = 15