#출력결과 : apple, banana, orange~~ kiwi, grape, melon!! 이렇게 end에 기본 값 대신 다른 문자열을 지정해주니 한 줄로 이어져 나옴을 알 수 있다.
<sys 모듈과 stdout, stderr> 1. sys 모듈 - 파이썬 인터프리터 및 파이썬 스크립트의 동작을 컨트롤 하고 인터프리터와 스크립터에서 발생한 에러 메세지를 다룰 수 있다. - 이 모듈에서는 표준입출력에 대한 stdin(입력 객체), stdout, stderr 등의 객체를 제공 2. stdout : 표준 출력 객체 - 기본적으로 print함수는 stdout에 출력됨, 하지만 print함수의 file파라미터를 사용하면 stdout이 아닌 다른 파일 객체에 출력할 수 있음 3. stderr : 표준 에러 출력 객체 - 프로그램에서 발생한 오류메세지는 이 stderr을 통해 출력 - stdout과 같이 print함수의 file파라미터를 사용하면 stdout이 아닌 다른 파일 객체에 출력할 수 있음
importsys
print("Hello, World!",file=sys.stdout)
print("Error: File not found.",file=sys.stderr)
#Hello, World!
#Error: File not found.
<ljust, rjust, zfill> - 문자열의 정렬 및 채우기 등의 문자열 메소드 - ljust : 문자열 왼쪽 정렬, 주어진 길이에 맞게 오른쪽을 공백으로 채우기 - rjust : 문자열 오른쪽 정렬, 주어진 길이에 맞게 왼쪽을 공백으로 채우기 - zfill : 주어진 길이에 맞게 왼쪽을 0으로 채우기
# ljust 예시
dict1={'apple':3,'banana':7,'cherry':1}
forkey,valueindict1.items():
print(key.ljust(10),str(value).ljust(5))
# 출력 결과
# apple 3
# banana 7
# cherry 1
# rjust 예시
dict1={'apple':3,'banana':7,'cherry':1}
forkey,valueindict1.items():
print(key.rjust(10),str(value).rjust(5))
# 출력 결과
# apple 3
# banana 7
# cherry 1
# zfill 예시
number='42'
print(number.zfill(5)) # '00042'
print(number.zfill(2)) # '42'
#rjust를 zfill처럼 사용하기
num=123
num_str=str(num)
result=num_str.rjust(10,'0')
print(result)# 0000000123
+) 사용자 입력을 통해서 값을 받게되면 type은 항상 문자열(숫자든 문자든)
<출력 포맷들>
print("{0:>10}".format(500))
# 0은 500을 의미하고 : >10은 10자리를 확보하고 오른쪽 정렬하며 빈 칸은 공백으로 채워서 출력한다는 의미
#출력 : 500
print("{0}".format(500)) # {0} 위치에 500 값 출력
print("{0:>10}".format(500))
# 0은 500을 의미하고 : >10은 10자리를 확보하고 우측 정렬하며 빈 칸은 공백으로 채워서 출력한다는 의미
# 출력 : 500
print("{0:>+10}".format(300))
print("{0:>+10}".format(-300))
print("{0:,}".format(3000000000000)) # 인덱스 값 천 단위 구분하여 출력
print("{0:+,}".format(-3000000000000)) # 음수기호, 천 단위 구분
print("{0:.2f}".format(3.14159265)) # 0번 인덱스 값을 소수점 이하 둘째 자리까지
print("{0:.2%}".format(0.25)) # 0번 인덱스값을 백분율 형태로 출력하고 소수점 둘째자리까지 출력
print("{0:.2f}".format(5/3))
<파일 입출력> - 물리적 저장 장치에 있는 데이터를 프로그램에서 읽거나 쓰는 것을 의미 - 프로그램에서 데이터를 영속적으로 저장하거나 다른 프로그램과 데이터를 주고받을 때 유용 - 파이썬에서 파일입출력은 내장함수 open()함수 사용 - 파일을 프로그램에서 읽거나 쓰고나서 무조건 close로 파일 닫기를 해줘야함
myfile=open("example.txt","w",encoding="utf8) # 파일 생성 또는 열기
ifmyfile:
myfile.write("Hello, World!\n") # 파일에 문자열 쓰기 (.write로 쓸 땐 줄바꿈 기호 넣어줘야함)
myfile.write("This is a sample file.\n")
myfile.close() # 파일 닫기
myfile=open("example.txt","a",encoding="utf8) # 이어쓰기 모드로 파일 열기
#"w"모드로 wirte하면 이전 글에 덮어씌우기 때문에 내용추가할 거면 a모드(append)로 이어써주면 됨
ifmyfile:
myfile.write("This is appended text.\n") # 파일에 내용 추가
myfile.close() # 파일 닫기
myfile=open("example.txt","r",encoding="utf8") # 파일 열기, r(읽기모드)
ifmyfile:
contents=myfile.read() # 파일 내용 전체 읽기
print(contents)
myfile.close() # 파일 닫기
withopen("example.txt","r")asmyfile:
contents=myfile.read()
print(contents)
# with문은 파일을 열고, 작업 마친 후 자동으로 파일을 닫아줌
myfile=open("example.txt","r",encoding="utf8")
lines=myfile.readlines() # 모든 줄을 읽어와서 list 형태로 저장
forlineinlines:
print(line,end="") # 읽어온 줄 출력. 줄바꿈 중복을 방지하기 위해 end="" 처리
myfile.close()
myfile=open("example.txt","r") # 파일 열기
ifmyfile:
forlineinmyfile:
print(line)# 줄바꿈 자동
myfile.close() # 파일 닫기
<pickle> - 객체를 직렬화하고 복원하는 라이브러리 - 프로그램 상에서 사용하는 데이터를 파일형태로 저장 - pickle을 사용하면 객체를 저장하고 다시 불러올 때, 객체를 구성하는 데이터랑 메소드를 포함해 그대로 복원할 수 있음 -> 객체의 일관성과 데이터 무결성을 보존하는 데 유용 - 파이썬의 내장모듈로 제공, dump()함수로 객체를 파일에 저장, load()함수로 파일에서 객체를 복원 - 보안상 안전하지 않을 수 있으니 신뢰할 수 있는 소스에서 받은 파일을 열어 pickle로 복원해야 함
importpickle
# 객체 생성
data={'name':'John','age':30,'gender':'male'}
# 객체를 파일에 저장
withopen('data.pickle','wb')asf:
pickle.dump(data,f) # data에 있는 정보를 객체 f에 저장
# 파일에서 객체를 불러오기
withopen('data.pickle','rb')asf:
loaded_data=pickle.load(f) # f에 있는 정보를 loaded_data에 불러오기
# 불러온 객체 출력
print(loaded_data)
withopen('data.pickle','rb')asf:
loaded_data=pickle.load(f) # f에 있는 정보를 loaded_data에 불러오기