Header Ads Widget

Ticker

6/random

Python Read Files

Python Read Files


Reading files in Python can be done in various ways, depending on the specific requirements of your task. 


Here are examples illustrating different methods for reading files:


Reading Entire File Content:

```python

# Open a file in read mode

with open("example.txt", "r") as file:

    content = file.read()

    print(content)

```


Reading Line by Line:

```python

# Open a file in read mode

with open("example.txt", "r") as file:

    for line in file:

        print(line.strip()) # strip() removes newline characters

```


Reading Lines into a List:

```python

# Open a file in read mode

with open("example.txt", "r") as file:

    lines = file.readlines()

    for line in lines:

        print(line.strip())

```


Using `seek()` to Move the Cursor:

```python

# Open a file in read mode

with open("example.txt", "r") as file:

    # Read the first 10 characters

    content_part1 = file.read(10)

    print(content_part1)


    # Move the cursor to the beginning

    file.seek(0)


    # Read the next 10 characters

    content_part2 = file.read(10)

    print(content_part2)

```


Using `tell()` to Get the Current Cursor Position:

```python

# Open a file in read mode

with open("example.txt", "r") as file:

    content_part1 = file.read(10)

    print(content_part1)


    # Get the current cursor position

    cursor_position = file.tell()

    print("Current Cursor Position:", cursor_position)

```


These examples demonstrate different approaches to read files in Python. The `with` statement is used to ensure that the file is properly closed after reading. Reading can be done all at once, line by line, or by reading lines into a list. The `seek()` method allows moving the cursor within the file, and `tell()` retrieves the current cursor position.

Post a Comment

0 Comments