logo

Датотечни објекти у Питхон-у

Датотечни објекат нам омогућава да користимо приступ и манипулишемо свим датотекама доступним корисницима. Може се читати и писати било које такве датотеке. Када операција датотеке не успе из разлога везаног за И/О, појављује се изузетак ИОЕррор. Ово укључује ситуације у којима операција није дефинисана из неког разлога као што је сеек() на тти уређају или писање датотеке отворене за читање. Датотеке имају следеће методе:
    опен(): 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() 
    реадлине([величина]) : 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() 
    реадлинес([сизехинт]) : 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() 
    тражити (помак од_где) : 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() 
    Атрибути:
      затворено: враћа логичку вредност која указује на тренутно стање фајл објекта. Враћа тачно ако је датотека затворена и нетачно када је датотека отворена. кодирање: Кодирање које користи ова датотека. Када се Уницоде стрингови уписују у датотеку, они ће бити конвертовани у низове бајтова користећи ово кодирање. режим: И/О режим за датотеку. Ако је датотека креирана коришћењем уграђене функције опен(), ово ће бити вредност параметра режима. име: Ако је фајл објекат креиран коришћењем опен(), име датотеке. нови редови: Датотечни објекат који је отворен у универзалном режиму новог реда има овај атрибут који одражава конвенцију новог реда која се користи у датотеци. Вредност за овај атрибут је 'р' 'н' 'рн' Ништа или торка која садржи све виђене типове новог реда. софтспаце : 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) 
Повезани чланак: Читање и писање у текстуалне датотеке у Питхон-у Референца: хттпс://доцс.питхон.орг/2.4/либ/блтин-филе-објецтс.хтмл