📝 Writing and Managing Files in Python: Creating, Writing, and Closing Files

File handling is one of the most essential skills in Python programming—whether you're logging data, saving user input, or managing configuration files. In this article, we'll explore how to create, write, and close files using Python, with clear examples and best practices.

đź“‚ Why File Handling Matters

In real-world applications, data often needs to be stored persistently. File handling allows you to:

  • Save output from your programs

  • Read configuration or input files

  • Log errors or events

  • Process large datasets without loading everything into memory

Python makes this process simple and intuitive.

🛠️ Creating and Opening Files

To work with files, Python provides the built-in open() function. Here's the basic syntax:

python

file = open("example.txt", "w")
  • "example.txt" is the file name.

  • "w" stands for write mode. If the file doesn’t exist, Python will create it. If it does exist, it will be overwritten.

Other modes include:

ModeDescription
"r"Read (default)
"w"Write (creates or overwrites)
"a"Append (adds to the end)
"x"Create (fails if file exists)

✍️ Writing to a File

Once the file is open in write mode, you can use .write() to add content:

python

file = open("example.txt", "w")
file.write("Hello, world!\n")
file.write("This is a second line.")

You can also write multiple lines using .writelines():

python

lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
file.writelines(lines)

⚠️ Note: You must include newline characters (\n) manually when using .write() or .writelines().

âś… Closing the File

Always close the file after you're done to free up system resources and ensure data is saved properly:

python

file.close()

Alternatively, use a with block to handle this automatically:

python

with open("example.txt", "w") as file:
    file.write("Using with block is cleaner!")

This ensures the file is closed even if an error occurs during writing.

đź§  Best Practices

  • âś… Use with open(...) for cleaner and safer code.

  • âś… Always handle exceptions using try-except blocks when working with files.

  • âś… Avoid hardcoding file paths—use os.path or pathlib for portability.

đź§Ş Real-World Use Case: Logging Errors

python

def log_error(error_message):
    with open("error_log.txt", "a") as log_file:
        log_file.write(f"{error_message}\n")

This simple function appends error messages to a log file—perfect for debugging or monitoring.

🚀 Final Thoughts

File handling is a foundational skill that unlocks countless possibilities in Python development—from data, ML pipelines to web apps. Mastering it early will make your code more robust and production-ready.

If you're exploring backend development or data analysis, file handling will be your everyday companion. Keep experimenting and building!

0
Subscribe to my newsletter

Read articles from Aryan Srivastava directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Aryan Srivastava
Aryan Srivastava