File Handling

File handling in Python allows you to work with files, reading from them, writing to them, and manipulating file paths.

Reading from Files

Reading from files in Python is a common operation. You can use the open() function to open a file and then read its content.

Here's an example of reading from a file:

Pythontry:
    with open("example.txt", "r") as file:
        content = file.read()
        print(content)
except FileNotFoundError as e:
    print("Error:", e)
    # Output: Contents of the file

The with statement is used to ensure that the file is properly closed after reading.

Writing to Files

Writing to files allows you to store data persistently. You can use the open() function with the mode set to "w" for writing.

Here's an example of writing to a file:

Pythontry:
    with open("example.txt", "w") as file:
        file.write("Hello, File!")
except IOError as e:
    print("Error:", e)
    # Creates or overwrites "example.txt" with the specified content

Be cautious with the mode "w" as it will overwrite the file if it already exists.

Working with File Paths

File paths are essential for navigating and manipulating files. Python provides the os module to work with file paths.

Here's an example of working with file paths:

Pythonimport os

file_path = "path/to/your/file.txt"

# Get the absolute path
absolute_path = os.path.abspath(file_path)

# Get the directory name
directory_name = os.path.dirname(file_path)

# Get the base name (filename)
file_name = os.path.basename(file_path)

print("Absolute Path:", absolute_path)
print("Directory Name:", directory_name)
print("File Name:", file_name)

Understanding and manipulating file paths is crucial for working with files in different directories.