Header Ads Widget

Ticker

6/random

Python File Handling

Python File Handling


File handling in Python involves operations like reading from and writing to files. 


Here are examples demonstrating basic file operations:


Writing to a File:

```python

# Open a file in write mode (creates a new file if it doesn't exist)

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

    file.write("Hello, this is a sample text.\n")

    file.write("Python file handling example.")

```


Reading from a File:

```python

# Open a file in read mode

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

    content = file.read()

    print(content)

```


Appending to a File:

```python

# Open a file in append mode (creates a new file if it doesn't exist)

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

    file.write("\nAppending more content to the file.")

```


Reading Line by Line:

```python

# Open a file in read mode

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

    lines = file.readlines()

    for line in lines:

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

```


Using `try` and `except` for Error Handling:

```python

try:

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

        content = file.read()

        print(content)

except FileNotFoundError:

    print("File not found.")

```


These examples cover writing, reading, and appending to files. The `with` statement is used for file handling, ensuring that the file is properly closed after operations. Reading from a file can be done either at once or line by line. Additionally, error handling with `try` and `except` helps manage situations like attempting to open a nonexistent file.

Post a Comment

0 Comments