본문 바로가기
코딩/파이썬

파이썬 파일입출력

by Song1234 2024. 3. 20.

1. 파일 열기

파일을 열려면 open 함수를 사용합니다.

f = open("파일명", "모드")

파일명: 열고자 하는 파일의 이름이나 경로 (파일이 없으면 만들어 준다.)
모드: 파일을 어떻게 열 것인지를 지정

모드 종류

  • r(read): 읽기 모드 (기본값)
  • w(write): 쓰기 모드 (파일이 있으면 덮어쓰기)
  • a(append): 추가 모드 (파일의 끝에 내용을 추가)

*+: 읽기와 쓰기 모드

파일 종류

  • b(binary): 바이너리 모드 (텍스트가 아닌 영상,이미지,등 바이너리 데이터를 읽고/쓸 때 사용 )
  • t(text): 일반적인 텍스트를 읽거나 쓸때 사용 생략가능(기본값)

사용

  • rt : 텍스트 파일 읽기 모드
  • wt : 텍스트 파일 쓰기 모드
  • ab : 바이너리 파일 추가 모드

위와같은 형태(모드+파일타입)로 사용할수 있다.

2. 파일 쓰기

f = open('example.txt', 'w')
f.write('Hello, Python!\n')
f.writelines(['Line1\n', 'Line2\n'])
f.close() # close를 써주어야 파일이 저장된다.

파일을 더이상 사용하지 않을때 파일.close() 로 파일을 종료 해 주어야한다.

f = open('data.txt', 'wt')
for i in range(10):
    f.write('파일 열기 테스트: ' + str(i) + '\n')
f.close()
print('data.txt 파일에 쓰기 완료!')

data.txt 파일에 쓰기 완료!

내용을 추가하려는 파일이 존재하지 않을경우 파일을 새로만들어 내용을 채운다.

3. with 문 사용하기

파이썬의 with 문을 사용하면 파일을 열고 작업을 수행한 후 자동으로 파일을 닫을 수 있습니다.

with open('./data/word.txt', 'w') as f: #  파일을 열고 f 라는 별칭을 붙여준다
    while True:
        data = input('단어를 입력하세요: ')
        if data.lower() == 'quit':
            break
        f.write(data + '\n')

단어를 입력하세요: apple
단어를 입력하세요: banana
단어를 입력하세요: orange
단어를 입력하세요: melon
단어를 입력하세요: berry
단어를 입력하세요: quit

with를 사용하면 with문이 끝날때 close가 자동으로 호출 되어서 close를 따로 써줄 필요가없다.


4. 파일 읽기

f = open('example.txt', 'r')
# content = f.read() # read()는 파일전체를 읽어온다.
content = f.read(10) # ()안에 값을 입력하면 해당값의 글자수 만큼만 읽어온다.
print(content)
f.close()

Hello, Pyt

f = open('example.txt', 'r')
while True:
    data = f.read(10)
    if not data:
        break
    print(data, end = '')

Hello, Python!
Line1
Line2

with  open('example.txt', 'r') as f:
    while True:
        data = f.read(10) # 10글자만 읽어들이고
        if not data: # 뒤에 데이터가 없다면
            break # 브레이크
        print(data, end = '') # 데이터가 있다면 모두출력

Hello, Python!
Line1
Line2

with open('./data/word.txt', 'r') as f:
    lines = []
    while True:
        line = f.readline() # readline(): 한줄 읽기
        if not line: # 데이터가 없다면 브레이크
            break
        if len(line.strip()) != 0: # 공백을 제거하고 len이 0 이아니라면
            print(line, end = '') # 라인 출력후
            lines.append(line.strip()) # 리스트에 추가

apple
banana
orange
melon
berry

print(lines)

['apple', 'banana', 'orange', 'melon', 'berry']

with open('./data/word.txt', 'r') as f:
    lines = f.readlines() # 모든라인 읽어오기
    print(lines)

['apple\n', 'banana\n', 'orange\n', 'melon\n', 'berry\n']

readline(): 라인 한줄 만 불러온다
readlines(): 모든 라인을 불러와 한줄씩 list에 담는다

문자를 저장할때마다 줄을 바꾸기 때문에 저장된 문자에 \n이 포함되어있다.

li = []
for i in lines:
    li.append(i.replace('\n', ''))
print(li)

['apple', 'banana', 'orange', 'melon', 'berry']

for 문으로 요소를 하나씩 불러와 replace를 사용해 \n을 빼고 다시 담아준다.

5. 예외 처리와 함께 사용하기


try:
    with open('nofile.txt', 'r') as f:
        content = f.read()
        print(content)
except FileNotFoundError:
    print('파일이 존재하지 않습니다')

파일이 존재하지 않습니다

'코딩 > 파이썬' 카테고리의 다른 글

변수 타입 어노테이션  (1) 2024.03.21
파일 입출력을 이용한 단어장 만들기  (0) 2024.03.21
파이썬 모듈  (0) 2024.03.20
파이썬 예외처리  (1) 2024.03.20
스페셜 메서드  (0) 2024.03.19