Python File Methods

Python File Methods

Python provides multiple methods that can be performed on a file object created using the open() method.

Syntax: file.method()

Here are all the methods with a short description for each of them:

  • read(n) – The read() method reads the file till the end if no parameter is passed. This can take an integer parameter that specifies the number of characters to be read the file.

  • write() – The write() method takes a string parameter and writes that string into the opened file. After finishing the operation, it returns the number of characters written.

  • close() – The close() method closes an opened file. However, Python won’t raise any error if the file that you are trying to close is already closed.

  • readable() – The readable() method is a binomial operation and it will return True if the file that you are trying to read can be read.

  • flush() – The flush() method clears the internal buffer of the opened file. Python is able to flush file automatically but the user can also choose to flush the file before closing it using this method.

Buffer is the part of the main memory that is used to hold data that is being sent from one place to another.

  • readline(n) – The readline() method reads one entire line from the opened file. This can also take one integer parameter to specify the number of characters to be read from the file.

  • readlines(n) – The readlines() method reads the file until the end. An integer parameter can be passed to limit the data or number of characters to be read from the opened file.

  • isatty() – The isatty() method will return True if the opened file is associated with a terminal device, if not then False.

  • detach() – The detach() method detaches the binary buffer from the TextIOBase. After detaching, it returns the detached binary buffer.

  • fileno() – The fileno() method returns an integer number that is used by Python to request input-output operations from the operating system.

  • writable() – The writable() method is similar to readable() method and will return True if you can write into the file.

  • tell() – The tell() method returns the location of the file.

  • writelines(lines) – The writelines() method takes a list as a parameter, and it will write the list of lines to the file.

  • seekable() – The seekable() method will return True if the file is seekable. The file is seekable if the access is allowed by the file to the file stream.

  • seek(offset, from) – The seek() method changes the position of the file handle to the specified position.

File handle is similar to a cursor, it tells Python from where the data should be written or read.

Tutorials for all brains!