0% completed
File methods in Python are essential for performing a variety of operations on files. Below is a detailed table that summarizes the various file methods available, providing a clearer understanding of each method's purpose and application.
Method | Description |
---|---|
close() | Closes the file. No further operations are allowed after the file is closed. |
flush() | Flushes the internal buffer to the disk, ensuring all in-memory changes are saved. |
fileno() | Returns the integer "file descriptor" that the OS uses for file I/O operations. |
isatty() | Checks if the file stream is connected to a terminal or tty device. |
next() | Retrieves the next line from the file, useful for iterating over each line. |
read([size]) | Reads up to size bytes from the file; reads till EOF if size is omitted. |
readline([size]) | Reads a single line up to size bytes from the file. A newline character marks the end of the line. |
readlines([sizehint]) | Reads lines from the file until EOF and returns them as a list. The sizehint can control the read size approximately. |
seek(offset[, whence]) | Moves the file cursor to the offset position relative to whence (start, current, end). |
tell() | Returns the current cursor position in the file. |
truncate([size]) | Truncates the file's size to size bytes. If size is omitted, truncates to the current position. |
write(str) | Writes a string str to the file. Does not return a value. |
writelines(sequence) | Writes a sequence of strings to the file, typically used with a list of strings. |
To demonstrate how some of these methods work, let's look at practical examples using seek()
and tell()
methods to manipulate and report file positions.
Explanation:
file = open('example.txt', 'r+')
: Opens example.txt
for both reading and writing.content = file.read(10)
: Reads the first 10 bytes from the file.print('First 10 bytes:', content)
: Displays the bytes read from the file.position = file.tell()
: Retrieves the current position in the file after reading.print('Current file position:', position)
: Shows the cursor's position in the file.file.seek(0)
: Moves the cursor back to the start of the file.first_line = file.readline()
: Reads the first line from the beginning of the file.print('First line:', first_line)
: Displays the line read from the file.file.close()
: Closes the file to free system resources.This example showcases how to use seek()
to manipulate the file cursor and tell()
to retrieve its position, illustrating practical file management operations in Python.
.....
.....
.....