Sign In
Programming Language

[Python] 입출력

Y
Yerim
카테고리
  1. Python

사용자 입출력

input

a = input()
b = input("안내_문구")
input은 사용자가 키보드로 입력한 모든 것을 문자열로 저장
괄호 안에 안내 문구를 입력하여 프롬프트를 띄울 수 있다

print

# 정수
a = 123
print(a) # 123

# 문자열
# 따옴표로 둘러싸인 문자열을 연속해서 쓰면 "+" 연산과 같음
print("life" "is" "too short")   # lifeistoo short
print("life"+"is"+"too short")   # lifeistoo short

# 문자열 띄어쓰기는 쉼표
print("life", "is", "too short") # life is too short

# 한 줄에 결괏값 출력 - end로 끝 문자 지정
for i in range(10):
    print(i, end=' ') # 0 1 2 3 4 5 6 7 8 9

파일 입출력

파일 생성

파일 열기
파일_객체 = open(파일_이름, 파일_열기_모드)
open 함수를 사용하여 파일의 이름파일 열기 모드를 설정할 수 있다
경로를 표현할 때
슬래시 (/): "C:/doit/새파일.txt”
역슬래시 두 개 (\\): "C:\\doit\\새파일.txt”
r + 역슬래시 (\): r"C:\doit\새파일.txt”
파일 열기 모드
파일열기모드
설명
r
읽기 모드: 파일을 읽기만 할 때 사용한다.
w
쓰기 모드: 파일에 내용을 쓸 때 사용한다.
a
추가 모드: 파일의 마지막에 새로운 내용을 추가할 때 사용한다.
파일 닫기
파일_객체.close()
close()를 사용해서 파일을 직접 닫아줄 수 있다
# file_with.py
with open("foo.txt", "w") as f:
    f.write("Life is too short, you need python")
with문을 함께 사용하면 with문을 벗어나는 순간 열린 파일 객체가 자동으로 닫힌다

파일 쓰기

# write_data.py
f = open("C:/doit/새파일.txt", 'w')
for i in range(1, 11):
    data = "%d번째 줄입니다.\n" % i
    f.write(data)
f.close()
‘w’ 모드로 파일을 열면 새로운 파일에 내용을 작성할 수 있다
write함수를 사용하면 데이터를 파일에 쓸 수 있다

파일 읽기

readline
# readline_all.py
f = open("C:/doit/새파일.txt", 'r')
while True:
    line = f.readline()
  if not line: break
  print(line)
f.close()
readline을 사용하면 파일을 한 줄 씩 읽을 수 있다
readlines
# readlines.py
f = open("C:/doit/새파일.txt", 'r')
lines = f.readlines()
for line in lines:
    line = line.strip()
    print(line)
f.close()
readlines는 파일의 모든 줄을 읽어서 각각의 줄을 요소로 가지는 리스트를 리턴
line = line.strip()를 사용하면 줄바꿈 문자를 제거할 수 있다
read
# read.py
f = open("C:/doit/새파일.txt", 'r')
data = f.read()
print(data)
f.close()
# read_for.py
f = open("C:/doit/새파일.txt", 'r')
for line in f:
    print(line)
f.close()
read는 파일의 내용 전체를 문자열로 리턴
for문과 함께 사용하면 파일을 줄 단위로 읽을 수 있다

파일에 새로운 내용 추가

# add_data.py
f = open("C:/doit/새파일.txt",'a')
for i in range(11, 20):
    data = "%d번째 줄입니다.\n" % i
  f.write(data)
f.close()
기존 값을 유지하면서 새로운 값을 추가할 때는 ‘a’ 모드로 열면 된다

프로그램 입출력

sys 모듈

# sys1.py
import sys

args = sys.argv[1:]
for i in args:
    print(i)
C:\doit>python sys1.py aaa bbb ccc
sys 모듈을 import하면 사용할 수 있다
sys 모듈의 argv는 프로그램 실행 시 전달된 인수를 의미
argv[0]sys1.py, argv[1]부터는 뒤에 따라오는 인수가 차례대로 argv 요소가 된다
Subscribe to 'Yerim-DevNote'
Subscribe to my site to be the first to receive notifications and emails about the latest updates, including new posts.
Join Slashpage and subscribe to 'Yerim-DevNote'!
Subscribe
👍