1 분 소요

파일 읽기, 쓰기

  • 읽기 모드 : r
  • 쓰기 모드 : w(파일이 존재하면 덮어쓰기, 없으면 새로 생성)
  • 추가 모드 : a(파일이 없으면 새로 생성, 있으면 값을 추가)

  • path 구분 : 상대경로(‘../’ : 이전 폴더, ‘./’:현재 폴더)
    • 절대경로 : ‘c:\user\abc’
fp = open("sample.txt", mode="w")
fp.write("hello python")
fp.close()
rfp = open("sample.txt", mode="r")
content = rfp.read()
rfp.close()

print(content)
    hello python
    
fp = open("test.txt", "r")
content = fp.read()
fp.close()
print(content)
  손흥민/20/박지성/30/김길동/40

 

test.txt 읽어서 다음과 같이 출력하세요

[‘손흥민’, ‘20’, ‘박지성’, ‘30’, ‘김길동’, ‘40’]

fp = open("test.txt", "r")
content = fp.read() # read() : 전체 내용을 읽기
fp.close()

print(content.split('/'))

    ['손흥민', '20', '박지성', '30', '김길동', '40']

 

fp = open("test.txt", "r")
content = fp.read(10)
print(content)

# fp.seek(0)
content = fp.read(10)
print(content)
fp.close()
    손흥민/20/박지성
    손흥민/20/박지성

 

with open('test.txt', 'r') as fp:
    content = fp.read()
    print(content.split('/'))
    ['손흥민', '20', '박지성', '30', '김길동', '40']

 

with open('test2.txt', 'r') as fp:
    content = fp.read(10)
    content = fp.read()
    
    print(content)
    print(type(content))
    print(list(content))

    ---------------------------------------------------------------------------

    FileNotFoundError                         Traceback (most recent call last)

    ~\AppData\Local\Temp/ipykernel_5020/69384570.py in <module>
    ----> 1 with open('test2.txt', 'r') as fp:
          2     content = fp.read(10)
          3     content = fp.read()
          4 
          5     print(content)
    

    FileNotFoundError: [Errno 2] No such file or directory: 'test2.txt'

 

with open('test2.txt', 'r') as fp:
    line = fp.readline() # 한라인을 읽어온다.
#     print(type(line))
#     print(line)
    while line:
        print(line, end='')
        line = fp.readline()
        
    Lorem Ipsum is simply dummy text of 
    the printing and typesetting industry.
    Lorem Ipsum has been the industry's standard
    dummy text ever since the 1500s, 
    when an unknown printer took a galley of
    type and scrambled it to make a type specimen book.

 

readlines() : 전체를 읽은 후 라인 단위로 리스트로 리턴

with open('test2.txt', 'r') as fp:
    contents = fp.readlines()
    
    print(contents)
    ['Lorem Ipsum is simply dummy text of \n', 'the printing and typesetting industry.\n', "Lorem Ipsum has been the industry's standard\n", 'dummy text ever since the 1500s, \n', 'when an unknown printer took a galley of\n', 'type and scrambled it to make a type specimen book.']

 


with open('./test2.txt', 'r') as fp:
    _str = []
    for line in fp:b
        _str.append(line)
    
    print(_str)
    ['Lorem Ipsum is simply dummy text of \n', 'the printing and typesetting industry.\n', "Lorem Ipsum has been the industry's standard\n", 'dummy text ever since the 1500s, \n', 'when an unknown printer took a galley of\n', 'type and scrambled it to make a type specimen book.']

파일 쓰기

with open('./test_write.txt', 'w') as fp:
    fp.write('say!!! \n')
with open('./test_write.txt', 'a') as fp:
    fp.write('goodbye!!! \n')
with open('./test_write2.txt', 'a') as fp:
    fp.write('goodbye!!! \n')

카테고리:

업데이트:

댓글남기기