WRITE FILES using Python! (.txt, .json, .csv) ✍
Table of Contents
Introduction
In this tutorial, we will learn how to write data to different file formats using Python, specifically .txt, .json, and .csv files. This is a fundamental skill for data handling and storage in programming, making it essential for anyone looking to work with data in Python.
Step 1: Writing to a .txt File
To start, we will write data to a plain text file.
-
Open a file in write mode:
- Use the
open()
function with the mode set to "w".
with open('example.txt', 'w') as file: file.write("Hello, this is a text file.")
- This code creates a file named
example.txt
and writes a string to it.
- Use the
-
Using absolute file paths:
- If you want to specify a location, use an absolute path.
with open('/path/to/your/directory/example.txt', 'w') as file: file.write("This is an absolute path example.")
- Replace
/path/to/your/directory/
with the actual path on your system.
-
Understanding file modes:
- "w" mode will overwrite any existing file.
- To create a new file without overwriting, use "x" mode:
with open('newfile.txt', 'x') as file: file.write("This file was created with mode 'x'.")
Step 2: Appending to a .txt File
If you want to add content to an existing file without erasing it, use "a" mode.
- Open a file in append mode:
with open('example.txt', 'a') as file: file.write("\nAdding another line to the text file.")
- This adds a new line to
example.txt
without deleting previous content.
- This adds a new line to
Step 3: Writing to a .json File
Next, we will write data to a JSON file, which is useful for structured data.
-
Import the json module:
import json
-
Prepare your data:
- Use a Python dictionary or list to organize your data.
data = { "name": "John", "age": 30, "city": "New York" }
-
Write to a JSON file:
with open('data.json', 'w') as json_file: json.dump(data, json_file, indent=4)
- This creates
data.json
with a structured format.
- This creates
Step 4: Writing to a .csv File
Finally, we will write data to a CSV file, which is commonly used for tabular data.
-
Import the csv module:
import csv
-
Prepare your data:
- Organize your data as a list of dictionaries or a list of lists.
data = [ ["name", "age", "city"], ["Alice", 25, "Los Angeles"], ["Bob", 30, "Chicago"] ]
-
Write to a CSV file:
with open('data.csv', 'w', newline='') as csv_file: writer = csv.writer(csv_file) writer.writerows(data)
- This creates
data.csv
with the specified content.
- This creates
Conclusion
In this tutorial, we covered how to write to .txt, .json, and .csv files using Python. Key points include:
- Use appropriate modes ("w", "a", "x") when opening files.
- Understand the structure of JSON and CSV files for effective data storage.
- Utilize the
json
andcsv
modules for handling specific file formats.
Next, you can explore reading from these files or handling exceptions for more robust programming practices. Happy coding!