Study/Python

입력과 출력문

coldtruthk 2024. 5. 17. 13:08

입력문과 출력문

 

변수가 들어갈 곳에 중괄호 {}를 넣고 마지막에 .format(변수)를 쓰면 된다.

여러 변수를 출력할 수 있는데 반드시 중괄호 {}의 갯수와 format안에 있는 변수 숫자는 같아야 한다.

 

height = 175
weight = 61
print('나의 키는 {}cm 이고 몸무게는 {}kg이다.'.format(height, weight))

나의 키는 175cm 이고 몸무게는 61kg이다.

print('{} and {}'.format('Python','Numpy'))
print('{1} and {0}'.format('cat','dog'))

Python and Numpy
dog and cat

 

print 문은 한줄에 결과 값을 계속 이어서 출력하려면 end를 사용해 끝 문자를 지정해야 한다.

for i in range(10):
    print(i, end = '')

0 1 2 3 4 5 6 7 8 9

print('010','1234','5678',sep="-")

010-1234-5678

number = 123.456789123456789
print("num : {}".format(number))
print("num : {:7.2f}".format(number))
print("num : {:0<8.2f}".format(number))
print("num :{:0>8.2f}".format(number))
print("num : {:*>8.2f}".format(number))

num : 123.45678912345679
num :  123.46
num : 123.4600
num :00123.46
num : **123.46

str = "Hong Gildong"
print(str)
print("{:/>20s}".format(str))
print("{:/<20s}".format(str))

Hong Gildong
////////Hong Gildong
Hong Gildong////////

 

open() 함수를 이용한 파일 입출력

 

  • 파일을 열 때는 기본적으로 with 문을 통해 open() 내장 함수를 호출한다.
  • with 문을 사용하지 않을 경우 파일 닫기를 스스로 해줘야 한다.
  • open() 내장함수는 첫번째 인자로는 파일명, 두번째 인자로는 모드를 받는다.
  • 파일에 데이터를 쓸 때는 w모드(기존에 있던 파일 데이터는 모두 사라짐)
  • read() 함수는 파일의 전체 데이터를 문자열로 반환한다.
animals = ['cat', 'dog', 'lion']
with open('animals.dat','w') as file:
    for animal in animals:
        file.write(animal+'\n')
with open('animals.dat') as file:
    print(file.read())

cat
dog
lion

 

파일을 줄 단위로 읽어야 할 때 for문을 사용해서 루프 돌릴 수 있다.

with open('animals.dat') as file:
    for animal in file:
        print(animal, end=' ')

 

파일을 줄 단위로 읽은 결과를 바로 배열에 저장하고 싶다면 splitlines() 메소드를 사용한다.

with open('animals.dat') as file:
    animals = file.read().splitlines()
    print(animals)

['cat', 'dog', 'lion']

 

파일 다루기

 

파일 객체 = open(파일 이름 혹은 경로/이름, 파일 열기 모드)
r(읽기 모드), w(쓰기 모드), a(추가모드 : 파일 마지막에 새로운 내용 추가), x파일 생성
    파일생성 : open('file_name.txt', 'x'), open('file_name.txt', 'w')

 

'Study > Python' 카테고리의 다른 글

프로그램 흐름제어  (3) 2024.03.27
컴프리헨션과 range()  (0) 2024.03.25
배열의 패킹과 언패킹  (0) 2024.03.25
문자열  (1) 2024.03.18
math 패키지 및 통계  (0) 2024.03.12