본문 바로가기

프로그래밍/Python

[Python] 파일 읽고 쓰기 방법

반응형

 파일 읽고 쓰기 예제??

txt파일이나 여러 파일들을 읽어서 프로그래밍하는 경우가 많이 존재한다.
이번에는 Python을 통해서 텍스트 파일을 읽어서 out.log파일로 써보도록 하자~!

우선 읽고자 하는 파일은 test.txt로 하고 
메모장에 test.txt에 
1
2
3
4
5
6
7
8
9

로 입력을 하고 파이썬 파일에 저장을 하자~!

infile_name = input('Please input file name : ')
outfile_name = "out.log"

with open(infile_name) as infile :
with open(outfile_name, "w") as outfile :
for in_line in infile.readlines():
outfile.write("read from '%s' : %s"%(infile_name, in_line))


여기서 (outfile_name, "w") <-- "w"는 반드시 소문자로 적어야 합니다.


그러면 out.log파일이 생성되고 결과는

read from 'test.txt' : 1
read from 'test.txt' : 2
read from 'test.txt' : 3
read from 'test.txt' : 4
read from 'test.txt' : 5
read from 'test.txt' : 6
read from 'test.txt' : 7
read from 'test.txt' : 8
read from 'test.txt' : 9

가 나오게 되네요.


for문 안에 다양한 프로그래밍을 할 수 있는 기반이 마련 되었습니다!! 

반응형