File Object in Python

File Object in Python

July 10, 2023 | permanent, python

An Object in Python: File Object #

ref These are just like another object with standard methods or interfaces- read(), write(), etc - . They allow interactions with underlying resource through the standard interface.

An object exposing a file-oriented API (with methods such as read() or write()) to an underlying resource. Depending on the way it was created, a file object can mediate access to a real on-disk file or to another type of storage or communication device (for example standard

  • input/output,

  • in-memory buffers,

  • sockets,

  • pipes, etc.).

    File objects are also called file-like objects or streams.

Synonyms: #

  1. File like objects
  2. Streams

Three types of File objects #

There are actually three categories of file objects:

  1. raw binary files,
  2. buffered () binary files and
  3. text files.

Their interfaces are defined in the io module. The canonical way to create a file object is by using the open() function. Glossary

File-oriented API #

ref You can address a file-oriented programming interface via normal calls open, read, write and close. So, when you send data to an object, it is written with write, when it is to be received, it is read, and when it is to be closed, close is used.

Methods #

ref close() Closes the file detach() Returns the separated raw stream from the buffer fileno() Returns a number that represents the stream, from the operating system’s perspective flush() Flushes the internal buffer isatty() Returns whether the file stream is interactive or not read() Returns the file content readable() Returns whether the file stream can be read or not readline() Returns one line from the file readlines() Returns a list of lines from the file seek() Change the file position seekable() Returns whether the file allows us to change the file position tell() Returns the current file position truncate() Resizes the file to a specified size writable() Returns whether the file can be written to or not write() Writes the specified string to the file writelines() Writes a list of strings to the file

TextIOWrapper #

ref A buffered text stream providing higher-level access to a BufferedIOBase buffered binary stream. It inherits TextIOBase.

file = open('test.txt', 'w') # file is called as Python File object
print(type(file))
# Output: <class '_io.TextIOWrapper'>

Reading big files #


Links to this note

Go to random page

Previous Next