logo

Python의 파일 객체

파일 객체를 사용하면 사용자가 액세스할 수 있는 모든 파일에 액세스하고 조작할 수 있습니다. 그러한 파일을 읽고 쓸 수 있습니다. I/O 관련 이유로 파일 작업이 실패하면 IOError 예외가 발생합니다. 여기에는 tty 장치에서 검색()을 수행하거나 읽기 위해 열린 파일을 작성하는 등의 이유로 작업이 정의되지 않은 상황이 포함됩니다. 파일에는 다음과 같은 방법이 있습니다.
    열려 있는(): Opens a file in given access mode.
     open(file_address access_mode) 
    Examples of accessing a file: A file can be opened with a built-in function called open(). This function takes in the file’s address and the access_mode and returns a file object. There are different types of access_modes:
      r:   Opens a file for reading only   r+:   Opens a file for both reading and writing   w:   Opens a file for writing only   w+:   Open a file for writing and reading.   a:   Opens a file for appending   a+:   Opens a file for both appending and reading
    When you add 'b' to the access modes you can read the file in binary format rather than the default text format. It is used when the file to be accessed is not in text. 읽기([크기]) : It reads the entire file and returns it contents in the form of a string. Reads at most size bytes from the file (less if the read hits EOF before obtaining size bytes). If the size argument is negative or omitted read all data until EOF is reached. Python
    # Reading a file f = open(__file__ 'r') #read() text = f.read(10) print(text) f.close() 
    readline([크기]) : It reads the first line of the file i.e till a newline character or an EOF in case of a file having a single line and returns a string. If the size argument is present and non-negative it is a maximum byte count (including the trailing newline) and an incomplete line may be returned. An empty string is returned only when EOF is encountered immediately. Python
    # Reading a line in a file f = open(__file__ 'r') #readline() text = f.readline(20) print(text) f.close() 
    readlines([sizehint]) : It reads the entire file line by line and updates each line to a list which is returned.Read until EOF using readline() and return a list containing the lines thus read. If the optional sizehint argument is present instead of reading up to EOF whole lines totalling approximately sizehint bytes (possibly after rounding up to an internal buffer size) are read. Python
    # Reading a file f = open(__file__ 'r') #readline() text = f.readlines(25) print(text) f.close() 
    쓰기(문자열) : It writes the contents of string to the file. It has no return value. Due to buffering the string may not actually show up in the file until the flush() or close() method is called. Python
    # Writing a file f = open(__file__ 'w') line = 'Welcome Geeksn' #write() f.write(line) f.close() 
    다양한 모드의 추가 예: Python
    # Reading and Writing a file f = open(__file__ 'r+') lines = f.read() f.write(lines) f.close() 
    Python
    # Writing and Reading a file f = open(__file__ 'w+') lines = f.read() f.write(lines) f.close() 
    Python
    # Appending a file f = open(__file__ 'a') lines = 'Welcome Geeksn' f.write(lines) f.close() 
    Python
    # Appending and reading a file f = open(__file__ 'a+') lines = f.read() f.write(lines) f.close() 
    쓰기 라인(시퀀스) : It is a sequence of strings to the file usually a list of strings or any other iterable data type. It has no return value. Python
    # Writing a file f = open(__file__ 'a+') lines = f.readlines() #writelines() f.writelines(lines) f.close() 
    말하다() : It returns an integer that tells us the file object’s position from the beginning of the file in the form of bytes Python
    # Telling the file object position f = open(__file__ 'r') lines = f.read(10) #tell() print(f.tell()) f.close() 
    탐색(오프셋 from_where) : It is used to change the file object’s position. Offset indicates the number of bytes to be moved. from_where indicates from where the bytes are to be moved. Python
    # Setting the file object position f = open(__file__ 'r') lines = f.read(10) print(lines) #seek() print(f.seek(22)) lines = f.read(10) print(lines) f.close() 
    플러시() : Flush the internal buffer like stdio‘s fflush(). It has no return value. close() automatically flushes the data but if you want to flush the data before closing the file then you can use this method. Python
    # Clearing the internal buffer before closing the file f = open(__file__ 'r') lines = f.read(10) #flush() f.flush() print(f.read()) f.close() 
    파일번호() : Returns the integer file descriptor that is used by the underlying implementation to request I/O operations from the operating system. Python
    # Getting the integer file descriptor f = open(__file__ 'r') #fileno() print(f.fileno()) f.close() 
    이사티() : Returns True if the file is connected to a tty(-like) device and False if not. Python
    # Checks if file is connected to a tty(-like) device f = open(__file__ 'r') #isatty() print(f.isatty()) f.close() 
    다음() : It is used when a file is used as an iterator. The method is called repeatedly. This method returns the next input line or raises StopIteration at EOF when the file is open for reading( behaviour is undefined when opened for writing). Python
    # Iterates over the file f = open(__file__ 'r') #next() try: while f.next(): print(f.next()) except: f.close() 
    자르기([크기]) : Truncate the file's size. If the optional size argument is present the file is truncated to (at most) that size. The size defaults to the current position. The current file position is not changed. Note that if a specified size exceeds the file's current size the result is platform-dependent: possibilities include that the file may remain unchanged increase to the specified size as if zero-filled or increase to the specified size with undefined new content. Python
    # Truncates the file f = open(__file__ 'w') #truncate() f.truncate(10) f.close() 
    닫다() : Used to close an open file. A closed file cannot be read or written any more. Python
    # Opening and closing a file f = open(__file__ 'r') #close() f.close() 
    속성:
      닫은: 파일 객체의 현재 상태를 나타내는 부울을 반환합니다. 파일이 닫혀 있으면 true를 반환하고 파일이 열려 있으면 false를 반환합니다. 부호화: 이 파일이 사용하는 인코딩입니다. 유니코드 문자열이 파일에 기록되면 이 인코딩을 사용하여 바이트 문자열로 변환됩니다. 방법: 파일의 I/O 모드입니다. open() 내장 함수를 사용하여 파일을 생성한 경우 이는 모드 매개변수의 값이 됩니다. 이름: 파일 객체가 open()을 사용하여 생성된 경우 파일 이름입니다. 개행 문자: 범용 개행 모드로 열린 파일 객체는 파일에 사용된 개행 규칙을 반영하는 이 속성을 갖습니다. 이 속성의 값은 'r' 'n' 'rn'입니다. 없음 또는 표시된 모든 개행 유형을 포함하는 튜플입니다. 소프트스페이스 : It is a boolean that indicates whether a space character needs to be printed before another value when using the print statement. Python
      f = open(__file__ 'a+') print(f.closed) print(f.encoding) print(f.mode) print(f.newlines) print(f.softspace) 
관련 기사 : Python에서 텍스트 파일 읽기 및 쓰기 참조: https://docs.python.org/2.4/lib/bltin-file-objects.html