본문 바로가기

Python

PhCharm - 파일 입출력

# 파일 입출력
# 지금까지 값을 입력받을때는
# 사용자가 직접 키보드로 입력하는 방식을 사용했고
# 값을 출력할때는 모니터 화면에 표시하는 방식을 사용했음

# 하지만, 값을 입력받거나 출력하는 방법은 이게 다가 아님
# 파일을 통해 값을 입력/출력할 수 있고
# 네트워크를 통해 값을 입력/출력할 수도 있음

# 프로그램 실행 중 생성된 데이터들은
# 주로 메모리 내에 존재하는데
# 프로그램 종료시 같이 소멸됨
# 데이터의 영속성persistence을 부여하기 위해서는
# 데이터를 저장장치에 보관해서
# 데이터가 소멸되지 않도록 하는 것이 중요!

# 파일쓰기 : 데이터를 파일에 기록
# 파일객체변수 = open(경로, 모드)        # py2
# with open(경로, 모드) as 파일객체변수  # py3

# 파일모드 : 파일작업 종류
# w(쓰기), a(추가쓰기), t(텍스트파일 쓰기),
# b(바이너리파일 쓰기)

# 파일쓰기 작업이 끝나면 반드시 close 해줘야 함
# 단, with문을 사용하는 경우 close 생략 가능

# 간단한 인삿말을 hello.dat라는 파일에 저장하기
f = open('hello.dat', 'w')  # 쓰기모드로 파일 생성
f.write('Hello, World!!')  # 생성한 파일에 내용기록
# 파일에 기록한 문자수가 출력
f.close()  # 기록이 끝나면 파일객체 닫음

# py3 방식으로 파일에 무언가 쓰기
# 한글 저장시 반드시 파일인코딩 지정!
with open('hello2.dat', 'w', encoding='utf-8') as f:
    f.write('안녕하세요, 세상아!')



# 성적 데이터 입력
name = input('이름')
kor = int(input('국어'))
eng = int(input('영어'))
mat = int(input('수학'))

# 파일에 저장
# 파일에 작성한 내용이 계속 남아있도록 하기위해
# 파일쓰기모드를 a로 설정
sj = f'{name}, {kor}, {eng}, {mat}\n'
with open('sungjuk.dat', 'a', encoding='utf-8') as f:
    f.write(sj)


emp_id = input('사번')
f_name = input('이름')
l_name = input('성')
h_date = input('입사일')
email = input('이메일')
sal = input('연봉')
dept_id = input('부서번호')

emp = f'{emp_id}|{f_name}|{l_name}|{h_date}|{email}|{sal}|{dept_id}\n'
with open('emp.dat', 'a', encoding='utf-8') as f:
    f.write(emp)

 

 

 

# 파일읽기: 파일 내 데이터 읽어오기
# 파일객체변수 = open(경로, 모드)        # py2
# with open(경로, 모드) as 파일객체변수  # py3

# 파일모드 : 파일작업 종류
# r(읽기, 생략가능), t(텍스트파일 읽기),
# b(바이너리파일 읽기)

# 파일 읽을떄 사용가능 함수
# read : 택스트파일의 내용을 모두 읽음
# readline : 텍스트파일의 내용을 한 줄씩 읽어옴 (반복문사용)
# readlines : 텍스트파일의 내용을 한 줄씩 모두 읽어옴

# 간단한 인삿말이 저장된 hello.dat 이라는 파일을 읽어 내용을 화면에 표시
f = open('hello.dat', 'r')
doc = f.read()
f.close()
print(doc)

with open('hello2.dat', encoding='utf-8') as f:
    doc = f.read()
print(doc)

with open('sungjuk.dat', encoding='utf-8') as f:
    doc = f.read()
print(doc)

with open('sungjuk.dat', encoding='utf-8') as f:
    while True:
        line = f.readline()
        if not line:
            break
        item = line.split(', ')
        out = f'{item[0]}/{item[1]}/{item[2]}/{item[3]}'
        print(out, end='')


with open('emp.dat') as f:
    while True:
        line = f.readline()
        if not line:
            break
        item = line.split('|')
        out = f'''
사원번호 : {item[0]}
이름 : {item[1]} {item[2]}
입사일 : {item[3]}
부서번호 : {item[6]}----------------------------'''
        print(out, end='')


with open('emp.dat') as f:
    lines = f.readlines()   # readlines를 사용하면 한번에 모든 내용을 독립적으로 불러올 수 있음

for line in lines:
    print(line)

# read() vs readlines()
# read() - 텍스트마이닝 작업시 사용
#          텍스트파일을 읽어서 불용어 제거, 형태소 분석시 유용
# readlines() - 데이터파일을 이용한 작업시 사용
#               csv, tsv 파일을 읽어서 부분처리시 유용

# 스티브잡스 연설문 출력

with open('stevejobs_en.txt', encoding='utf-8') as f:
    doc = f.read()

print(doc)

# 핫도그대회 수상자 파일 출력
with open('csv/hotdog-winners.csv', encoding='utf-8') as f:
    f.readline()        # skip header
    lines = f.readlines()

for line in lines:
    print(line)

# hanb.co.kr 사이트에서 '새로운 도서' 정보를 크롤링해서 newbooks.csv 로 저장하세요
import requests
from lxml import html

url = 'https://www.hanbit.co.kr/store/books/new_book_list.html'

res = requests.get(url)
text = html.fromstring(res.text)

print(res.text)

titles = []
writers = []
prices = []

for title in text.cssselect('p.book_tit a'):
    # print(title.text_content())
    titles.append(title.text_content())


for writer in text.cssselect('p.book_writer'):
    # print(writer.text_content())
    writers.append(writer.text_content())

for price in text.cssselect('span.price'):
    # print(price.text_content())
    prices.append(price.text_content())

with open('newbooks.csv', 'w', encoding='utf-8') as f:
    for i in range(len(titles)):
        data = f'{titles[i]},{writers[i]},{prices[i]}\n'
        f.write(data)

'Python' 카테고리의 다른 글

PhCharm - pickle  (0) 2022.05.18
PhCharm - csv , json, binary  (0) 2022.05.17
PyCharm - except  (0) 2022.05.17
PyCharm - 모듈  (0) 2022.05.17
PyCharm - comprehension  (0) 2022.05.17