Python

file

haventmetyou 2023. 10. 11. 15:09

파일에 문자열 쓰기, 읽기

# 파일 쓰기
file = open('hello.txt', 'w')
file.write('Hello, world!')
file.close()

# 파일 읽기
f = open('hello.txt', 'r')
s = f.read
print(s)

f.close()

# 자동으로 파일 객체 닫기
with open('hello.txt', 'r') as f:
    s = f.read()
    print(s)

 

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

# 반복문으로 문자열 여러 줄을 파일에 쓰기
with open('hello.txt', 'w') as file:
    for i in range(3):
        file.write( 'Hello, world! {0}\n'.format(i) )
        
Hello, world! 0    # 출력 값
Hello, world! 1
Hello, world! 2

# 리스트에 들어 있는 문자열을 파일에 쓰기
lines = ['안녕하세요.\n', '파이썬\n', '코딩 도장입니다.\n']

with open('hello.txt', 'w') as file:
    file.writelines(lines)
    
안녕하세요.    # 출력 값
파이썬
코딩 도장입니다. 
    
# 파일 내용을 한 줄씩 리스트로 가져오기
with open('hello.txt', 'r') as file:
    lines = file.readlines()
    print(lines)
    
['안녕하세요.\n', '파이썬\n', '코딩 도장입니다.\n']    # 실행 결과

animals = ['cat\n', 'dog\n', 'fish\n', 'bird']
# 파일의 내용 한 줄씩 읽기
with open('hello.txt', 'r') as f:
    line = None
    while line !='':
        line = f.readline()
        print(line.strip('\n'))
        
cat    # 실행 결과
dog
fish
bird

with open('hello.txt', 'r') as f:
    for line in f:
        print(line.strip('\n'))
        
cat    # 실행 결과
dog
fish
bird

# 파일 객체는 이터레이터, 변수 여러 개에 저장하는 언패킹 가능

animals = ['cat\n', 'dog\n', 'fish\n', 'bird']

f = open('hello.txt', 'r')
a, b, c, d = f
print(a, b, c, d)

 

파이썬 객체를 파일에 저장, 가져오기
# 파이썬 객체 파일에 저장
import pickle

name = 'James'
age = 17
address = '서울시 서초구'
scores = {'kor':90, 'eng':95, 'mat':85, 'sci':82}

with open('james.p', 'wb') as f:
    pickle.dump(name, f)
    pickle.dump(age, f)
    pickle.dump(address, f)
    pickle.dump(scores, f)

실행 결과

전체 주석 처리

영역 지정 - ctrl + /

# 객체 읽기
with open('james.p', 'rb') as f:
    name = pickle.load(f)
    age = pickle.load(f)
    address = pickle.load(f)
    scores = pickle.load(f)
    print(name)
    print(age)
    print(address)
    print(scores)
    
James    # 실행 결과
17
서울시 서초구
{'kor': 90, 'eng': 95, 'mat': 85, 'sci': 82}