ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 18. File 다루기
    공부합시다!/python 2023. 2. 16. 00:14
    728x90

    Python은 빅데이터 및 인공지능에 쓰일 만큼 그 범용성이 크게 확장이 되어 있습니다.

    그 기본이 되는 파일 다루기에 대해서 살펴보겠습니다.

    파일 읽기, 쓰기가 대표적인 작업 입니다.

     

    # 파일 읽기, 쓰기
    # 읽기 모드 : r, 쓰기 모드(기존 파일 삭제), w 추가모드(파일 생성 또는 추가) : a
    
    # 파일 읽기'.
    
    # 예제 1
    f = open('./resource/review.txt', 'r')
    content = f.read()
    print(content)
    # 반드시 close 리소스 반환
    f.close()
    print(dir(f))
    
    print('*'*80)
    
    # 예제 2 : with문을 이용하면 리소스 자동반환
    with open('./resource/review.txt', 'r') as f:
      c = f.read()
      print(c)
      print(list(c))
    
    print("*"*100)
    
    # 예제 3
    with open('./resource/review.txt', 'r') as f:
      for c in f:
        print(c.strip())
    
    print("*"*100)
    
    # 예제 4
    with open('./resource/review.txt', 'r') as f:
      content = f.read()
      print(">", content)
      content = f.read()  # 내용 없음.
      print(">", content)
    
    
    # 예제 5
    with open('./resource/review.txt', 'r') as f:
      line = f.readline()   # 한줄만 읽어옴
      print(line)
    
    print(">"*100)
    with open('./resource/review.txt', 'r') as f:
      line = f.readline()
      while line:
        print(line, end = ">>>>>>>")
        line = f.readline()
    
    print(">"*100)
    
    # 예제 6
    with open('./resource/review.txt', 'r') as f:
      contens = f.readlines()   # 한줄만 읽어옴
      print(content)
      for c in content:
        print(c, end="**************")
    
    print(">"*100)
    
    # 예제 7
    with open('./resource/score.txt', 'r') as f:
      score = []
      for line in f:
        score.append(int(line))
      print(score)
    print("Average :  {:6.3}".format(sum(score)/len(score)))
    
    
    # 파일 쓰기
    
    # 예제 1
    with open('./resource/text1.txt', 'w') as f:
      f.write('first make file\n')
    
    print(">"*100)
    
    # 예제 2
    with open('./resource/text1.txt', 'a') as f:
      f.write('second line\n')
    
    # 예제 3
    from random import randint
    with open('./resource/text2.txt', 'w') as f:
      for cnt in range(6):
        f.write(str(randint(0, 50)))
        f.write('\n')
    
    
    # 예제 4
    # writelines : 리스트 -> 파일로 저장
    with open('./resource/text3.txt','w') as f:
      list = ["kim\n", "lee\n", "park\n"]
      f.writelines(list)
    
    # 예제 5
    # print 문 활용하여 파일 쓰기
    
    with open('./resource/text4.txt','w') as f:
      print("Test Contests1!", file=f)
      print("Test Contests2!", file=f)

    728x90

    '공부합시다! > python' 카테고리의 다른 글

    19. Excel 및 CSV 파일 다루기  (0) 2023.02.17
    17. 예외처리  (0) 2023.02.16
    16. Module과 Package  (0) 2023.02.14
    15. Class 상속  (0) 2023.02.13
    14. Class  (0) 2023.02.10
Designed by Tistory.