파일 사용

매일 공부(ML)·2022년 1월 8일
0

Python

목록 보기
20/38

[파일 사용]

1) 파일에 문자열 쓰기
파일객체 = open(파일이름, 파일모드)
파일객체.write('문자열')
파일객체.close()

file = open('hello.txt', 'w')    # hello.txt 
파일을 쓰기 모드(w)로 열기. 파일 객체 반환
file.write('Hello, world!')      # 파일에 문자열 저장
file.close()                     # 파일 객체 닫기

Hello, world!

2) 파일에서 문자열 읽기

파일객체 = open(파일이름, 파일모드)
변수 = 파일객체.read()
파일객체.close()

file = open('hello.txt', 'r')    # hello.txt 파일을 읽기 모드(r)로 열기. 파일 객체 반환
s = file.read()                  # 파일에서 문자열 읽기
print(s)                         # Hello, world!
file.close()                     # 파일 객체 닫기

3)자동으로 파일 객체 닫기

with open(파일이름, 파일모드) as 파일객체:
    코드
 ex)
 
with open('hello.txt', 'r') as file:    # hello.txt 파일을 읽기 모드(r)로 열기
    s = file.read()            # 파일에서 문자열 읽기
    print(s)                           # Hello, world! 

4)문자열 여러 줄을 파일에 쓰기, 읽기

with open('hello.txt', 'w') as file:    # hello.txt 파일을 쓰기 모드(w)로 열기
    for i in range(3):
        file.write('Hello, world! {0}\n'.format(i))

Hello, world! 0
Hello, world! 1
Hello, world! 2

5)리스트에 들어있는 문자열을 파일에 쓰기
파일객체.writelines(문자열리스트)

lines = ['안녕하세요.\n', '파이썬\n', '코딩 도장입니다.\n']

with open('hello.txt', 'w') as file:    # hello.txt 파일을 쓰기 모드(w)로 열기
    file.writelines(lines)

안녕하세요.
파이썬
코딩 도장입니다.

6)파일의 내용을 한 줄씩 리스트로 가져오기

변수 = 파일객체.readlines()

with open('hello.txt', 'r') as file:    # hello.txt 파일을 읽기 모드(r)로 열기
    lines = file.readlines()
    print(lines)

['안녕하세요.\n', '파이썬\n', '코딩 도장입니다.\n']

7) 파일의 내용을 한 줄씩 읽기

변수 = 파일객체.readline()

with open('hello.txt', 'r') as file:    # hello.txt 파일을 읽기 모드(r)로 열기
    line = None    # 변수 line을 None으로 초기화(이유?
    while line != '':
        line = file.readline()
        print(line.strip('\n'))    # 파일에서 읽어온 문자열에서 \n 삭제하여 출력

안녕하세요.
파이썬
코딩 도장입니다.

8)for반복문으로 파일의 내용을 줄 단위로 읽기

with open('hello.txt', 'r') as file:    # hello.txt 파일을 읽기 모드(r)로 열기
    for line in file:    # for에 파일 객체를 지정하면 파일의 내용을 한 줄씩 읽어서 변수에 저장함
        print(line.strip('\n'))    # 파일에서 읽어온 문자열에서 \n 삭제하여 출력

안녕하세요.
파이썬
코딩 도장입니다.

9)파이썬 객체를 파일에 저장하기, 가져오기
i)피클링(pickling) :객체-->파일 저장
ii)언피클링(unpickling): 파일-->객체 읽기

10)피클링(pickling) with dump메서드

import pickle
 
name = 'james'
age = 17
address = '서울시 서초구 반포동'
scores = {'korean': 90, 'english': 95, 'mathematics': 85, 'science': 82}
 
with open('james.p', 'wb') as file:    # james.p 파일을 바이너리 쓰기 모드(wb)로 열기
    pickle.dump(name, file)
    pickle.dump(age, file)
    pickle.dump(address, file)
    pickle.dump(scores, file)

11)언피클링(unpickling)

import pickle
 
with open('james.p', 'rb') as file:    # james.p 파일을 바이너리 읽기 모드(rb)로 열기
    name = pickle.load(file)
    age = pickle.load(file)
    address = pickle.load(file)
    scores = pickle.load(file)
    print(name)
    print(age)
    print(address)
    print(scores)

james
17
서울시 서초구 반포동
{'korean': 90, 'english': 95, 'mathematics': 85, 'science': 82}
  • EX
with open('words.txt', 'r') as file:
    for line in file:
        words=line.split()
        for word in words:
            if 'c' in word:
                print(word.strip(',.'))

참고 | 파일 객체는 이터레이터
파일 객체는 이터레이터입니다.
따라서 변수 여러 개에 저장하는 언패킹(unpacking)도
가능합니다.


>>> file = open('hello.txt', 'r')
>>> a, b, c = file
>>> a, b, c

('안녕하세요.\n', '파이썬\n', '코딩 도장입니다.\n')
물론 a, b, c = file과 같이 사용하려면 hello.txt에는
문자열 3줄이 들어있어야 합니다.
즉, 할당할 변수의 개수와 파일에 저장된
문자열의 줄 수가 일치해야 합니다.

profile
성장을 도울 아카이빙 블로그

0개의 댓글