2.2.3 Python 코드 예제 3

학습내용

- 파일을 데이터 읽고 쓰기

- 여러 줄에 statement 입력

- 반복 실행

 

소스코드

"""

Python code example 03

File input and output, multiple statements on a line

Iterative execution of a task

"""

### MAIN PROGRAM ========================================

i1=1+1+1+1+1+\

   1+1+1+1+1

i2=21

with open('test-in.txt','w') as f1:

    for i in range(i1,i2):

        x,y=i,1./float(i)

        f1.write('{} {}\n'.format(x,y))

with open('test-out.txt','w') as f2:

    with open('test-in.txt','r') as f1:

        for line in f1:

            x,y=map(float,line.split())

            f2.write('x, x(dB)= {} {}\n'.format(x, 20.*math.log10(y)))

### END MAIN PROGRAM =====================================

 

소스코드 실행결과

- test-in.txt 파일

10 0.1

11 0.09090909090909091

12 0.08333333333333333

13 0.07692307692307693

14 0.07142857142857142

15 0.06666666666666667

16 0.0625

17 0.058823529411764705

18 0.05555555555555555

19 0.05263157894736842

20 0.05

 

- test-out.txt 파일

x, 1/x(dB)= 10.0 -20.0

x, 1/x(dB)= 11.0 -20.8278537031645

x, 1/x(dB)= 12.0 -21.5836249209525

x, 1/x(dB)= 13.0 -22.278867046136735

x, 1/x(dB)= 14.0 -22.92256071356476

x, 1/x(dB)= 15.0 -23.521825181113627

x, 1/x(dB)= 16.0 -24.082399653118497

x, 1/x(dB)= 17.0 -24.60897842756548

x, 1/x(dB)= 18.0 -25.105450102066122

x, 1/x(dB)= 19.0 -25.57507201905658

x, 1/x(dB)= 20.0 -26.020599913279625

 

소스코드 실행결과

여러 줄에 걸쳐 statement 배치

끝에 \추가. \ 다음 시작 칸은 임의.

i1=1+1+1+1+1+\

   1+1+1+1+1

 

with open('test-in.txt','w') as f1:

- 파일 test-in.txt f1 명칭으로  write모드로 open 코드 블록(: 시작됨) 수행되면 close

- Interpreter에서 파일 open, read, close  연습

>>> f1 = open('test-in.txt','w')

>>> f1.read()

'10 0.1\n11 0.09090909090909091\n12 0.08333333333333333\n13 0.07692307692307693\n14 0.07142857142857142\n15 0.06666666666666667\n16 0.0625\n17 0.058823529411764705\n18 0.05555555555555555\n19 0.05263157894736842\n20 0.05\n'

>>> f1.seek(0,0)

>>> f1.readlines()

['10 0.1\n',

 '11 0.09090909090909091\n',

 '12 0.08333333333333333\n',

 '13 0.07692307692307693\n',

 '14 0.07142857142857142\n',

 '15 0.06666666666666667\n',

 '16 0.0625\n',

 '17 0.058823529411764705\n',

 '18 0.05555555555555555\n',

 '19 0.05263157894736842\n',

 '20 0.05\n']

>>> f1.close()

 

f1.read() 파일의 모든 줄을 읽은 ( 줄의 \n 포함) 모두 공백없이 이어 붙여서 1개의 문자열을 만든 f1.read() assign

f1.readlines() 줄의 내용을 문자열로 만든 이를 list (다른 언어에서 배열) 만든다. Python에서는 배열을 a = [1, 2, 3, 4, 5]처럼 중괄호와 comma 사용하여 표현

 

for i in range(i1,i2):

 i i1에서부터 i2-1까지 1 증가할 코드블록 수행

 

f1.write('{} {}\n'.format(x,y))

파일 f1 변수 x, y 기록

{} {} x, y 대응되는 위치(placeholder)

\n 기록후 다음 줄로 진행

.format(x,y) x, y순서로 같은 줄에 기본(default) 형식(format)으로 기록

 

for line in f1:

- 파일을 열면 자동적으로 f1 정보에 f1.readlines() 명령어로 생성되는 다음과 같은 list 내부적으로 만들어진다.

['10 0.1\n',

 '11 0.09090909090909091\n',

 '12 0.08333333333333333\n',

 '13 0.07692307692307693\n',

 '14 0.07142857142857142\n',

 '15 0.06666666666666667\n',

 '16 0.0625\n',

 '17 0.058823529411764705\n',

 '18 0.05555555555555555\n',

 '19 0.05263157894736842\n',

 '20 0.05\n']

 

- for line in f1: 문은 string 변수 line f1 내용을 첫줄부터 순차적으로 assign하고 다음의 코드블록을 수행

 

f2.write('x, x(dB)= {} {}\n'.format(x, 20.*math.log10(y)))

파일 f2 write() 괄호 안의 내용 기록. {}{} format()안에 있는 요소에 대응.

1 item 기록 : write() format 안쓰면 1개의 string 들어갈 있다. 따라서 숫자를 string으로 바꾼 \n 추가하여 다음 줄로 넘어가게

  f2.write(str(x)+'\n')