파일을 생성하거나 읽고 쓰는 경우 아래와 같이 현재 위치를 원하는 폴더로 지정해 놓아야 한다

(필자는 Python 저장 경로는 c드라이브의 pywork라는 폴더로 설정했다)

cd C:\pywork

 

myFile.txt파일을 생성하고 write('w')할 수 있는 객체 f 생성 후 내용 작성

f = open('myFile.txt', 'w')
f.write('This is my first file.')
f.close()

 

myFile.txt를 read('r')할 수 있는 객체 f 생성 후 내용 읽기

f = open('myFile.txt', 'r')
file_text = f.read()
f.close()
print(file_text)

->
This is my first file.

 

 

위와 같은 방법으로 파일 생성 후 다른 내용을 담아 보았다

f = open('two_times_table.txt', 'w')
for num in range(1,6):
    format_string = "2 x {0} = {1}\n".format(num, 2*num)
    f.write(format_string)
f.close()
f = open("two_times_table.txt")
line = f.readline()
while line:
    print(line, end = "")
    line = f.readline()
f.close()

->
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10

 

# lines = f.readlines() -> list형식으로 담김

f = open("two_times_table.txt")
lines = f.readlines()
f.close()
print(lines)

->
['2 x 1 = 2\n', '2 x 2 = 4\n', '2 x 3 = 6\n', '2 x 4 = 8\n', '2 x 5 = 10\n']

 

 

f = open("two_times_table.txt")
lines = f.readlines()
f.close()
for line in lines:
    print(line, end="")
    
->
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10

 

 

파일을 담은 객체를 그대로 사용 (코드 간소화)

f = open("two_times_table.txt")
for line in f:
    print(line, end="")
f.close()

->
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10

 

with as 키워드 사용

파일을 다루는 처리를 할때는 필수적으로 파일 오픈(open) 파일 닫기(close) 과정을 거치게 되는데 실수로 close하지 않는 경우가 종종 발생한다. 이런 경우를 대비해 with as 구문을 사용하여 해당 구문이 끝나면 자동으로 닫히게 되어서 이러한 실수를 줄일 수 있다

with open('myTextFile3.txt', 'w') as f:
    for num in range(1, 6):
        format_str = "3 x {0} = {1}\n".format(num, 3*num)
        f.write(format_str)
with open('myTextFile3.txt', 'r') as f:
    for line in f:
        print(line, end="")
        
->
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
3 x 4 = 12
3 x 5 = 15
반응형

+ Recent posts