Quick Introduction Read and Writing File in Python

This code demonstrates essential file operations in Python:

Using with guarantees the file is closed properly, even if errors occur. This prevents "resource leaks," where open files remain unused and consume system resources.

The code example showcases these concepts by:

Key Benefit:

Automatic file closing with with simplifies file handling and improves code reliability.


# Sample data to write to the file

data = input("Text to write to file: ")


# Open the file in write mode with context manager (no need for explicit close)

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

    # Write data to the file

    file.write(data)


    # You can access the file object within the 'with' block

    print(f"File name: {file.name}")


# Read the contents of the file after writing (assuming the file wasn't closed yet)

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

    contents = file.read()

    print(f"\nContents of the file:\n{contents}")


For example, when you run the code, you will get the following results for the input:


$ python3 example3.py

Text to write to file: testing, testing, testing, 1, 2, 3...

File name: sample_file.txt


Contents of the file:

testing, testing, testing, 1, 2, 3...


Looking to expand your Python knowledge? I recommend checking out the book "Mastering Learning Python 3: In Five Minutes." This resource offers a beginner-friendly approach with short, focused lessons that can help you grasp the fundamentals of Python 3 programming. (*** Now available on Amazon ***)