read() & write() methods, tell() & seek() methods

 read() & write() methods, tell() & seek() methods

In Python, file objects have several methods that are useful for reading and manipulating file content. Here's an explanation of the `read()`, `write()`, `tell()`, and `seek()` methods:


### 1. `read(size=-1)` Method:


The `read()` method reads and returns the content of the file. You can specify the number of bytes to read as an optional parameter (`size`). If `size` is not provided or is negative (`-1`), the entire file is read.


```python

# Read the entire file

with open('file.txt', 'r') as file:

    content = file.read()


# Read only the first 100 characters

with open('file.txt', 'r') as file:

    content = file.read(100)

```


### 2. `write(str)` Method:


The `write()` method writes a string to the file. If the file is opened in text mode (`'t'`), the argument must be a string. If the file is opened in binary mode (`'b'`), the argument must be a bytes-like object.


```python

# Write a string to a file

with open('output.txt', 'w') as file:

    file.write("Hello, World!")

```


### 3. `tell()` Method:


The `tell()` method returns the current position of the file cursor, indicating the byte offset from the beginning of the file. It's useful to know where you are in the file while reading or writing.


```python

with open('file.txt', 'r') as file:

    content = file.read(100)

    print(file.tell())  # Print the current position of the cursor

```


### 4. `seek(offset, whence=0)` Method:


The `seek()` method changes the file cursor position. `offset` specifies the number of bytes to move, and `whence` specifies the reference position for the offset. `whence` can take one of the following values:

- `0` (default): Absolute file positioning from the beginning of the file.

- `1`: Relative file positioning from the current cursor position.

- `2`: Relative file positioning from the end of the file.


```python

with open('file.txt', 'r') as file:

    file.seek(10)  # Move cursor to the 10th byte from the beginning of the file

    content = file.read(100)

    print(content)

```


Here, the `seek(10)` method moves the cursor to the 10th byte of the file, and then `read(100)` reads the next 100 characters from that position.


These methods provide precise control over reading and writing operations and cursor positioning within a file. Remember to handle exceptions and ensure proper file closure after performing operations to maintain code reliability and data integrity.


Comments

Popular posts from this blog

Programming in Python