What are the attributes of a file object in Python?



A file object has a lot of attributes. You can see a list of all methods and attributes of the file object here: https://docs.python.org/2.4/lib/bltin-file-objects.html. Following are some of the most used file object methods −

  • close() - Close the file.

  • next() - When a file is used as an iterator, typically in a for loop (for example, for line in f: print line), the next() method is called repeatedly. This method returns the next input line, or raises StopIteration when EOF is hit.

  • read([size]) - Read at most size bytes from the file.

  • readline([size]) - Read one entire line from the file.

  • seek(offset[, whence]) - Set the file's current position, like stdio's fseek(). The whence argument is optional and defaults to 0 (absolute file positioning); other values are 1 (seek relative to the current position) and 2 (seek relative to the file's end).

  • tell() - Return the file's current position, like stdio's ftell().

  • write(str) - Write a string to the file.

  • writelines(sequence) - Write a sequence of strings to the file.

Following are file object's most used attributes −

  • closed - bool indicating the current state of the file object.

  • encoding - The encoding that this file uses.

  • mode - The I/O mode for the file.

  • name - If the file object was created using open(), the name of the file. Otherwise, some string that indicates the source of the file object


Advertisements