티스토리 뷰

파일 쓰기

import os

man = []
other = []

"""
파일 읽기
"""
try :
    data = open('sketch.txt')


    for each_line in data :
        try :
            (role, line_spoken) = each_line.split(':', 1)
            line_spoken = line_spoken.strip()
            if role == 'Man' :
                man.append(line_spoken)
            elif role == 'Other Man' :
                other.append(line_spoken)


        except ValueError:
            pass

    data.close()

except IOError:
    print('The data file is missing!')

"""
파일 쓰기
"""
try :
    out_man = open('man_data.txt', 'w')
    out_other = open('other_data.txt', 'w')

    print(man, file=out_man)
    print(other, file=out_other)


except IOError :
    pass

finally :
    out_man.close()
    out_other.close()
    

line_spoken = line_spoken.strip()
파이썬의 문자열은 불변형, 따라서 공백을 제거한 문자열이 새로 만들어지고 line_spoken 이 다시 참조한다.

finally는 반드시 실행된다.
with 문 사용해서 파일 작업하기

with를 사용하면 finally스위트를 사용할 필요가 없다.

참고 : PEP 343 -- The "with" Statement

"""
파일 쓰기
"""
try :
    with open('man_data2.txt', 'w') as out_man :
        print(man, file=out_man)
    with open('other_data2.txt', 'w') as out_other :
        print(other, file=out_other)

except IOError as ioerr :
    print('File error : ' + str(ioerr))
"""
파일 쓰기
"""
try :
    with open('man_data2.txt', 'w') as out_man , open('other_data2.txt', 'w') as out_other   :
        print(man, file=out_man)
        print(other, file=out_other)

except IOError as ioerr :
    print('File error : ' + str(ioerr))


데이터 피클링하기

dump로 저장하고 load로 읽는다

이진데이타로 쓴다.

import io
import pickle

man = []
other = []

"""
파일 읽기
"""
try :
    data = open('sketch.txt')

    for each_line in data :
        try :
            (role, line_spoken) = each_line.split(':', 1)
            line_spoken = line_spoken.strip()
            if role == 'Man' :
                man.append(line_spoken)
            elif role == 'Other Man' :
                other.append(line_spoken)


        except ValueError:
            pass

    data.close()

except IOError as ioerr :
    
    print('The data file is missing!')
    print('File error : ' + str(ioerr))
    
"""
피클 데이타  쓰기
"""    
try :
    with open('man_pickle.txt', 'wb') as out_man :
        pickle.dump(man, out_man)
        
except IOError as ioerr :
    print('File error : ' + str(ioerr))
except pickle.PickleError as perr:
    print('Pickle error : ' + str(perr))

이진데이타를 읽는다.

import nester
import pickle

new_man = []

"""
피클 데이타 읽기
"""
try :
    with open('man_pickle.txt', 'rb') as man_file:
        new_man = pickle.load(man_file)

except IOError as ioerr :
    print('File error : ' + str(ioerr))
except pickle.PickleError as perr:
    print('Pickle error : ' + str(perr))

nester.print_lol(new_man) 

이진데이타 예시 man_pickle.txt

댓글