ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • File
    python/기본 2022. 5. 1. 20:51
    f = open('test.txt', 'w')
    f.write('test')
    # 아래도 가능하다.
    # print('I am print', 'Mike', file=f, sep='#')
    f.close()
    
    with open('test.txt', 'w') as f:
        f.write('test\n')
        
    ####################################################################    
    with open('test.txt', 'r') as f:
    	all = f.read()
        # f.read(2) # 2 bytes 만 읽어옴
    print(all)    # with 문 밖에서도 all 참조 가능 !!!
    
    # 라인 단위로 읽기
    with open('test.txt', 'r') as f:
        while True:
            line = f.readline().strip()
            print(line)
    
            if not line:
                break    
    
    with open('robot.txt', 'r') as f:
        lines: list[str] = f.readlines()
        for l in lines:
            print(l.strip())
    
    ####################################################################    
    # 쓰기 / 읽기 모드로 파일 열기
    s = """\
    AAA
    BBB
    CCC
    DDD
    """
    
    # 쓰고 나서 읽기
    with open('test.txt', 'w+') as f:
        f.write(s)
        f.seek(0)
        print(f.read())
        
    # 읽고 나서 쓰기    
    with open('test.txt', 'r+') as f:
        print(f.read())
        f.write(s)

    'python > 기본' 카테고리의 다른 글

    os, pathlib, glob, shutil  (0) 2022.05.01
    Template, Csv  (0) 2022.05.01
    Class  (0) 2022.05.01
    __name__ 과 __main__  (0) 2022.05.01
    Library  (0) 2022.05.01

    댓글

Designed by Tistory.