본문으로 바로가기
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

6. 파일 다루기


1) 파일 입출력의 기초


- 파일 입출력 기본 문법

파일 객체 = open(파일 이름, 열기모드)
파일 객체.close()

열기모드
r      읽기모드
w    쓰기모드
a     추가모드

☞ 2줄 객체닫기 : 파이썬은 프로그램 종료시 모든 파일 객체를 자동으로 닫아주기 때문에 생략가능하나 w모드로 열린파일은 명시적으로 닫아줘야함.


2) 파일 다루기


- 파일 저장 위치를 지정하지 않으면 프로그램과 같은 위치에 저장됨.

- fileFirst.txt와 fileSecond.txt 파일을 생성하고 파일을 출력하는 프로그램.

import os

def makeFile(filename, message, mode):
    a=open(filename, mode)
    a.write(message)
    a.close()

def openFile(filename):
    b=open(filename, "r")
    lines = b.readlines()
    for line in lines:
        print(line)
    b.close()

makeFile("fileFirst.txt", "This is my first 1\n", "w")
makeFile("fileFirst.txt", "This is my first 2\n", "w")
makeFile("fileFirst.txt", "This is my first 3\n", "w")
makeFile("fileSecond.txt", "This is my second 1\n", "a")
makeFile("fileSecond.txt", "This is my second 2\n", "a")
makeFile("fileSecond.txt", "This is my second 3\n", "a")

print("write fileFirst.txt")
print("--------------------------------")
openFile("fileFirst.txt")
print("--------------------------------")

print("\n")

print("write fileSecond.txt")
print("--------------------------------")
openFile("fileSecond.txt")
print("--------------------------------")

☞ fileFirst.txt는 쓰기모드("w")이기 때문에 마지막에 기록한 내용만 남게 됨.

☞ fileSecond.txt는 추가모드("a")이기 때문에 기록한 모두가 내용에 남음.

☞ 가장 처음에 추가하는 os 모듈은 파일 삭제 기능을 지원.

☞ shutil 모듈을 이용하면 파일의 이동과 복사가 가능함.