Table of Contents » Reference Materials : File Object Methods
File Object Methods
Python file object methods are a set of functionalities provided by file objects, which are created when a file is opened using Python's built-in open() function. These methods enable interaction with the file content in various ways. Key methods include read(size) to read a specified number of bytes or the entire file if size is omitted, readline() to read a single line, and readlines() to read all lines into a list. For writing, write(string) writes a string to the file, and writelines(list) writes a list of strings. The seek(offset) method is used to change the file position, allowing you to read or write at a specific point in the file. tell() returns the current file position. It's important to manage resources efficiently by closing the file after operations with close(). Additionally, files can be used with a context manager (with statement) for automatic closing. These methods are fundamental for efficient file handling in Python, enabling developers to perform a wide range of file operations with ease.
File Method | Description |
---|---|
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 |