본문 바로가기

PYTHON

File I/O, 예외처리 개념

File I/O

* handle : 권한

 

filename = 'romeo.txt'
f = open(filename) # mode default read

 

  • import os
    os.getcwd() 현재 작업중인 폴더명을 가져옴
    os.chdir('folder name') 현재 폴더를 augument 폴더로 바꿈
    os.path.basename(path) augument path의 파일명을 가져옴
    os.path.dirname(path) 폴더명
  • os에 따른 path mark 처리os.path.join('a','b')
    import os
    path = os.path.join('c:\temp','test1.txt')
    print(path)
    
    # >>> 'c:\temp\\test1.txt'
  • f.close()
    • 사용 완료 후, 파일 메모리 해제
      filename = 'romeo.txt'
      f1 = open(filename)
      f2 = open('supplier0.csv')
      f1.close()
      f2.close()​
  • without close
    • with 구문 끝날 때, 파일 메모리 해제
      filename = 'romeo.txt'
      
      with open(filename) as f:
      	fline = f.read()
          print(fline)​
  • File Handle for Read
    • 파일을 읽기모드로 열었을 때,
    • 파일을 sequence of string으로 취급
      # 파일 내의 \n과 print의 \n이 있다.
      f = open('romeo.txt')
      for i in f:
          print(i)
          
      f = open('romeo.txt')
      for i in f:
          print(i.strip())
          # print(i, end='')
  • Whole File Read
    • 파일의 각 line 읽기는 1번만 가능
    • read()
      • 한 문장으로 가져옴.
        f = open('romeo.txt')
        result = f.read()
        >>> result
        'But soft what light through yonder window breaks\nIt is the east and Juliet is the sun\n
        Arise fair sun and kill the envious moon\nWho is already sick and pale with grief\n'
    • readlines() 
      • 한 줄씩 가져온다.
        f = open('romeo.txt')
        flines = f.readlines()
        print(flines)
        
        >>> ['But soft what light through yonder window breaks\n', 
        'It is the east and Juliet is the sun\n', 
        'Arise fair sun and kill the envious moon\n', 
        'Who is already sick and pale with grief\n']
    • reaeline()
      f = open('romeo.txt')
      fline = f.readline()
      while fline:
          print(fline, end='')
          
      '''
      # := 바다코끼리 연산자, 3.8 이상부터 지원
      f = open('romeo.txt')
      while fline:=f.readline():
          print(fline, end='')
      '''
  • File Write
    • 기존의 내용이 사라짐
      filename = 'romeo.txt' 
      f = open(filename, 'w') 
      s = 'That thou her maid art far more fair than she:Be not ger maid since she is envious;' 
      f.write(s) 
      f.close()​
  • File Append
    • 기존의 내용이 유지
      filename = 'romeo.txt'
      f = open(filename, 'a')
      s = 'That thou her maid art far more fair than she:Be not ger maid since she is envious;'
      
      f.write(s)
      f.close()​

# 실습

# 11주차 실습
# 'romeo.txt' 파일을 read하여 각 단어의 수를 count 하시오.

# dict로 작성
# key : word(단어), value: count(단어의 개수)
# {'But' : 1, 'is': 3, ...}

# 완성된 dict의 key(단어)를 words.txt파일로 저장
# Key(단어)만 저장, 1줄에 word 1개씩

# 저장할 dict와 단어 개수를 셀 변수
d= {}
count = 0

with open('romeo.txt') as f:
    # 단어 하나씩 저장
    result = f.read().split()

    # 각 단어가 몇개씩 있는지 비교                         
    for i in result:
        for j in result:
            if i == j:
                # 같은 단어가 있으면 1씩 추가
                count += 1
        # 단어 key값에 개수 value를 저장
        d[i] = count
        # 다시 세기 위해서 초기화
        count = 0

    print(d)

# word.txt에 key값만 저장
with open('words.txt', 'w') as af:
    for i in d.keys():
        af.write(i+'\n')
        

# 단어장, 단어의 뜻을 저장하기
# 원하는 단어만 적도록
with open('words.txt') as rf:
    words = rf.readlines()

    
with open('end_dict.txt','w') as af:
    for k in words:
        aword = k.strip()
        mean = input(f'{aword}(s:skip,q:quit:) ')
        if mean == 's':
            continue
        elif mean == 'q':
            break
        else:
            af.write(f'{aword}:{mean}\n')

'''

word_dict = dict() # empty dict
with open('romeo.txt') as f:
    while fline:=f.readline():
        lines = fline.split()
        for w in lines:
            # print(w) # word

            #dict에 단어 추가
            if w not in word_dict:
                word_dict[w] = 1
            else:
                word_dict[w] += 1 # word count

# print(word_dict)

with open('words.txt', 'a') as af:
    for k in word_dict.keys():
        af.write(k + '\n')
'''

 

예외처리

try:
    처리 구문
except:
    에러날 때 처리 구문
    
# Error를 알 경우
try:
    처리 구문
except FileNotFoundError:
    에러날 때 처리 구문

 

'PYTHON' 카테고리의 다른 글

Pandas  (0) 2021.12.03
Docstring, Scope, Module, File I/O 개념  (0) 2021.11.12
Set, 집합, Function, Parameter, Argument, Return 개념  (0) 2021.11.05