Writing an Array to CSV in Python (One Column)
This article demonstrates how to write a one-dimensional Python array to a CSV file using the csv
module.
Setting Up the Environment
Ensure you have Python installed on your system. The csv
module is part of the standard library, so no additional installation is required.
Writing the Array to CSV
The following Python code illustrates the process:
import csv # Sample array my_array = [1, 2, 3, 4, 5] # Specify the CSV file name csv_file_name = 'my_data.csv' # Open the CSV file in write mode with open(csv_file_name, 'w', newline='') as csv_file: csv_writer = csv.writer(csv_file) # Write each element of the array to a separate row for element in my_array: csv_writer.writerow([element]) |
Explanation
- Import the
csv
module: This line imports the necessary functions for working with CSV files. - Create a sample array: This line defines a one-dimensional array named
my_array
containing numbers. - Specify the CSV file name: The
csv_file_name
variable holds the name of the CSV file to be created. - Open the CSV file: The
with open(...)
statement opens the CSV file in write mode (‘w’) and ensures proper file closure, even if exceptions occur. - Create a CSV writer object: The
csv.writer(csv_file)
creates a writer object to handle writing data to the CSV file. - Write array elements to rows: The loop iterates through each element in the array and writes it to a separate row in the CSV file using the
writerow()
method.
Output
After running this code, you will find a CSV file named ‘my_data.csv’ in your working directory with the following content:
1 2 3 4 5
Conclusion
This simple example demonstrates how to write a one-dimensional Python array to a CSV file with each element on a separate row. You can easily adapt this code for arrays with different data types and for writing to other file formats using Python’s diverse data handling capabilities.