[python] File I/O

markyang92·2021년 8월 30일
1

python

목록 보기
29/43
post-thumbnail

open()

f = open(file, mode='MODE', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) 

f.close()
returnvalue
성공FILE object
실패exception OSError([arg])

argumentDescription
filepath-like object
modeDescribed at below the table

modeDescription초기 fp.seek(0,os.SEEK_CUR)
'r'open for reading (default)0
r+읽고 쓰기 모드, 하지만 파일이 없으면 FileNotFoundError Exception 발생0
'w'open for writing, truncating the file first
파일의 제일 처음에 새로 씀
0
'x'open for exclusive creation, failing if the file already exists
existing file이 있으면 IOError Exception 발생
'a'open for writing, appending to the end of the file if it exists==fp.seek(0, os.SEEK_END)
'b'binary mode
't'text mode (default)
'+'open for updating (reading and writing)
'w+b'open and truncate the file

Text I/O

  • Text I/O는 str object 생성.
  • encoding, decoding을 지정할 수 있고, Platform-specific newline character를 지정할 수 있다.
  1. 간단한 open() 예제
f = open("myfile.txt", "r", encoding="utf-8")

Binary I/O ('b')

  • Binary I/O (also called buffered I/O)는 bytes-like object를 사용해 bytes object를 생성한다.
    • No encoding, No decodeing
  1. 간단한 open() 예제
f = open("myfile.jpg", "rb")
  1. In-memory binary stream는 또한 BytesIO(https://docs.python.org/3/library/io.html#io.BytesIO) objects를 사용가능하다.
f = io.BytesIO(b"some initial binary data: \x00\x01")

RAW I/O (buffering=0)

  1. 간단한 open( ) 예제
f = open("myfile.jpg", "rb", buffering=0)

read 작업

fd = open('myfile.txt','r',encoding='utf-8')

fd.close()


혹은

with open('myfile.txt', 'r', encoding='utf-8') as f:
    c = f.read()
    print(c)

fd.readlines(): 리스트 반환

fd=open('samplefile','r')
fd_line= fd.readlines()
print( fd_line )

fd.close()

# ===== 출력 ===== #
['FROM centos\n', '\n', 'ENV container docker\n', '\n', 'RUN yum -y update; yum clean all\n', 'RUN yum -y install systemd; yum clean all; \\\n', '(cd /lib/systemd/system/sysinit.target.wants/; for i in *; do [ $i == systemd-tmpfiles-setup.service ] || rm -f $i; done); \\\n', 'rm -f /lib/systemd/system/multi-user.target.wants/*;\\\n', 'rm -f /etc/systemd/system/*.wants/*;\\\n', 'rm -f /lib/systemd/system/local-fs.target.wants/*; \\\n', 'rm -f /lib/systemd/system/sockets.target.wants/*udev*; \\\n', 'rm -f /lib/systemd/system/sockets.target.wants/*initctl*; \\\n', 'rm -f /lib/systemd/system/basic.target.wants/*;\\\n', 'rm -f /lib/systemd/system/anaconda.target.wants/*;\n', '\n', 'VOLUME ["/sys/fs/cgroup"]\n', 'CMD ["/usr/sbin/init"]\n', '\n']
  • \n 개행 문자까지 전부 들어간다.

fd.readline(): 개행 문자 한 줄 읽음

  1. sample.txt
    1 라인의 간단한 문장
1| helloworld
fd=open('sample.txt', mode='r')
print(fd.readline())
print(fd.readline())
# === 출력 === #
helloworld
               <-- 다읽어도 익셉션 발생 하지 않음!
# =========== # 
  • 그래서 readline()을 사용 할 때는, 한 줄 읽고 if not line: break 시키자
fd=open('sample.txt', 'r')
while True:
    line=fd.readline()
    if not line:
        break
    print(line,end='')


fd.close()

# ==== 출력 ==== #
helloworld

write 작업

fd=open('sample2.txt',mode='w')

fd.write('한 줄')

fd.close()
$ cat sample2.txt
한 줄

writelines(): list -> write

fd=open('sample2.txt', mode='w')
w_list=['hello\n','world!']

fd.writelines(w_list)

fd.close()
$ cat sample2.txt
hello
world

fprintf() 처럼 사용하기

fd=open('sample2.txt', 'w')
print('hello world!', file=fd)
fd.close()
$ cat sample2.txt
hello world!

seek

  • C의 systemcall을 공부해봤으면 익숙한 함수
  • 파일 포인터의 위치를 셋한다.
fp.seek(offset, whence)
seek argumentDescription
offsetwhence로 부터 몇 바이트 offset 할 것?
whence기준. os 모듈로 부터 3가지 키워드를 사용할 수 있음
0 | os.SEEK_SET: 파일의 시작
1 | os.SEEK_CUR: 파일 포인터의 현재 위치
2 | os.SEEK_END: 파일의 끝
  • 예시
import os
json_fp = open('json1.json','r')
json_fp.seek(0,os.SEEK_SET) # json_fp.seek(0,0)

....

권한 설정


파일 만들때 에러 처리

profile
pllpokko@alumni.kaist.ac.kr

0개의 댓글