[python] python3 힘들게 배우기 #4

7 분 소요

영어로 쓰기 힘들 때, 새롭게 글을 시작한다. 그래도 최소한 한 story에 2개 이상의 ex를 넣으려고 한다. 그나저나 이 책 엄청나게 기초부터 자세하다.

ex13. parameter, unpacking, variable

from sys import argv
script, first, second = argv
print("script is called:", script)
print("Your first variable is:", first)
print("Your second variable is:", second)

import의 개념이 처음으로 등장한다. 여기서는 argv module을 import하는데, argv는 argument variable이다. 두번째 줄에서 script, first, second 는 임의로 결정한 변수들이고 거기다 argv를 넣는 것을 unpacking이라고 한다. 이렇게 하면 ? 저렇게 세 개의 variable에 input을 받을 수 있게 된다.

위 파일을 ex13.py로 저장한 후에 실행할 때는 여느 때의 python ex??.py 와 달리, firstsecond 인수까지 함께 실행해야 한다. 즉 지금까지 실행명령에 사용되었던 ex??.py가 바로 스크립트인 것이고, python ex13.py one two 와 같이 타이핑한 후 엔터를 눌러야(즉 사용한다고 선언한 variable과 같은 수의 argument를 입력한 후에야만) 에러 없이 실행되게 된다.

script is called: ex13.py
Your first variable is: one
Your second variable is: two

.py로 끝나는 파일은 스크립트라고 하고, import 어쩌구저쩌구를 모듈(module)이라고 한다. 즉 필요한 모듈만 임포트함으로서 python각 스크립트들이 가벼워질 수 있다.

input()은 스크립트 실행 도중에 값을 받는 것이고, argv는 실행 시 넣는 것에서 차이가 있다. *argv를 통해 커맨드 라인에서 타이핑하는 값은 모두 string이므로, argv에서 숫자를 넣고 싶다? int(1)이라고 입력해야 함.

ex14. input과 argv조합하기

input 과 argv를 조합하면 아래와 같이 사용할 수도 있다.

from sys import argv
script, user = argv
prompt = '> '
print(f"Hi, {user}. This is {script} script.")
print("What is your favorite movie?")
movie = input(prompt)
print(f"You likes {movie}!")

실행할 때는 script(파일명) 과 user까지 입력하는 것을 잊지말자. 위 파일을 ex14로 저장한 후에 powershell에서 python ex14.py Tom 이라고 실행시키면

Hi, Tom. This is ex14.py script.
What is your favorite movie?
> Titanic
You likes Titanic!

이렇게 사용할 수 있다.

ex15. 파일 읽기

script 내부에서의 method를 통해 실제 파일을 불러오고, 그 내용을 읽을 수 있는 방법이 있다. 이 때 파일을 불러오는 것을 open(), 읽는 것을 read()라고 한다. 두 방법의 차이는 무엇일까? open() method는 마치 음반가게에서 씨디를 하나 고르는 것과 같다. CD를 골라도(open) 당신이 CD Player가 아닌 한 그 내용을 들을 수는 없다. 이 때 불러온 CD에 read() method를 통해서 그 내용을 읽을 수 있게 된다.

아래의 예제는 바로 전 ex에서 배웠던 argv 및 input method를 이용해 같은 file을 ‘하나의script내에서’ 두 번 불러오는 과정에 대한 실습이다. 한 개의 파일을 두 번 open()할 수 있는 것에 주목하자.

from sys import argv
script, file_name = argv
my_file = open(file_name)
print(f"Your file is {file_name}.")
print("and the contents of file is below.")
print(my_file.read())
print("Type your file name again.")
file_name_2 = input("> ")
my_file_2 = open(file_name_2)
print(my_file_2.read())

이렇게 작성 후, ex15.py로 저장하자.

같은 폴더에, txt파일을 하나 만든 뒤

<<<This is txt file contents.>>>

라고 적어넣은 후 ex15_sample.txt로 저장하자.

이후 ex15.py를 실행시킨다. 두 개의 arg를 통해 실행해야 하므로 당연히 python ex15.py ex15_sample.txt 를 통해 실행시키자. 결과는 아래와 같이 나온다.

Your file is ex15_sample.txt.
and the contents of file is below.
<<<This is txt file contents.>>>
Type your file name again.
> ex15_sample.txt
<<<This is txt file contents.>>>

아직 from, import에 대해서는 자세히 다루지 않으므로 그냥 sys라는곳에서 argv라는 module을 갖다 쓰는구나 정도로 이해하면 된다.

ex16. 파일 읽고 쓰기

파일에 관련된 method 들을 살펴보자.

open — 파일 열기

read — 파일 읽기

readline — 파일 중 1줄만 읽기

write(‘어쩌구저쩌구’) — ‘어쩌구저쩌구’ 라고 쓰기

truncate — 파일 내용지우기 (파일 자체지우는게 아님)

seek() — 파일에서 특정 위치 찾기. 보통 쓰기 전에.. 찾는 용도

close — 파일 닫기

파일 하나를 열고 → 지우고 → 다시 쓰고 → 닫는 시나리오를 수행해 보자.

텍스트 파일을 하나 만들고 아무 내용이나 쓴 후 ex16_sample.txt로 저장하자.

이후 다음과 같이 ex16.py를 작성하자.

from sys import argv
script, file_name = argv
txt = open(file_name, 'w')
print(f"You just opened {file_name }.")
txt.truncate()
print(f"You just emtpied {file_name }.")
print("Type three lines.")
line1 = input("Line 1:")
line2 = input("Line 2:")
line3 = input("Line 3:")
txt.write(line1+"\n"+line2+"\n"+line3)
print("Closing the file")
txt.close()

python ex16.py ex16_sample.txt 로 실행하자.

결과는 아래와 같다.

You just opened ex16_sample.txt.
You just emtpied ex16_sample.txt.
Type three lines.
Line 1:a
Line 2:b
Line 3:c
Closing the file

a,b,c 는 직접 input한 것이다. 이제 다시 ex16_sample.txt를 열어보면

a
b
c

로 파일 내용이 변경되어 있다.

주목할 것은, open() method의 두 번째 arg로 ‘w’를 넣었다는 것이다. 이것은 파일을 writable하게 열었다는 것을 뜻하며, 해당 arg를 넣지 않고 그냥 open()을 하고 파일을 수행하면 아래와 같은 에러 메시지를 볼 것이다.

You just opened ex16_sample.txt.
Traceback (most recent call last):
  File "ex16.py", line 8, in <module>
    txt.truncate()
io.UnsupportedOperation: File not open for writing

open() method의 두 번째 인자로는 ‘w’, ‘r’, ‘a’ 가 있으며 각각 쓰기, 읽기, 덧대기(append)를 의미한다. 추가적으로 +가 붙은 ‘w+’, ‘r+’, ‘a+’가 있다. 자세한 사항은 https://stackoverflow.com/questions/1466000/python-open-built-in-function-difference-between-modes-a-a-w-w-and-r를 참고하자.

위 링크를 참조해 보면, ‘w’ 로 여는 순간 file자체는 truncate된다. 위 코드에서 truncate은 불필요한 line인 셈이다.

보기좋게 정리한 표가 있다.

                  | r   r+   w   w+   a   a+
------------------|--------------------------
read              | +   +        +        +
write             |     +    +   +    +   +
write after seek  |     +    +   +
create            |          +   +    +   +
truncate          |          +   +
position at start | +   +    +   +
position at end   |                   +   +

태그:

카테고리:

업데이트:

댓글남기기