In this topic, we will explore the process of writing and creating files in Python. We'll cover everything from basic file creation and writing operations to more advanced techniques such as working with different file formats and handling exceptions.
To create a new text file in Python, you can use the open()
function with the "w"
mode. This mode creates a new file if it doesn’t exist or truncates the file if it already exists.
# Create a new text file and write content to it
with open("new_file.txt", "w") as file:
file.write("Hello, world!\n")
file.write("This is a new file.")
"w"
).write()
method to write content to the file.write()
appends the content to the file.If you want to add content to an existing file without overwriting its existing content, you can use the "a"
mode for append.
# Append content to an existing text file
with open("existing_file.txt", "a") as file:
file.write("\nAppending new content.")
"a"
).write()
method to append new content to the end of the file.To write data to a CSV (Comma-Separated Values) file in Python, you can use the csv
module. This module provides a writer
object to write data to CSV files efficiently.
import csv
# Write data to a CSV file
data = [
["Name", "Age", "City"],
["Alice", 30, "New York"],
["Bob", 25, "Los Angeles"]
]
with open("data.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerows(data)
csv.writer()
function to create a CSV writer object.writerows()
method to write data to the CSV file.JSON (JavaScript Object Notation) files are commonly used for storing and exchanging data. Python provides the json
module to work with JSON files efficiently.
import json
# Write data to a JSON file
data = {"name": "Alice", "age": 30, "city": "New York"}
with open("data.json", "w") as file:
json.dump(data, file)
json.dump()
function to serialize a Python dictionary object into JSON format and write it to a JSON file.When writing to files, various exceptions can occur, such as PermissionError
, FileNotFoundError
, etc. It’s crucial to handle these exceptions gracefully to prevent program crashes and handle errors effectively.
try:
with open("nonexistent_directory/new_file.txt", "w") as file:
file.write("Writing to a new file.")
except FileNotFoundError:
print("Directory not found")
except PermissionError:
print("Permission denied")
except Exception as e:
print("An error occurred:", e)
try-except
block to handle potential exceptions that may occur when writing to the file.FileNotFoundError
and PermissionError
, as well as a generic Exception
for any other unexpected errors.In this topic, we've covered the process of writing and creating files in Python. We started with the basics of creating and writing text files, including appending content to existing files. Then, we explored writing to different file formats such as CSV and JSON, leveraging the csv and json modules.
We also discussed the importance of handling file-related exceptions gracefully to ensure the robustness of our code when writing to files. By understanding these concepts and techniques, you're equipped to effectively write and create files in Python for various purposes. Happy Coding!❤️