Python provides built-in functionality to read and write CSV (comma-separated values) files. CSV files are commonly used to store data in a tabular format, with each row representing a data record and each column representing a data field.
Here is an example of how to read a CSV file in Python:
|
import csv
# Open the CSV file
with open('data.csv', 'r') as file:
# Create a CSV reader object
reader = csv.reader(file)
# Loop through each row in the CSV file
for row in reader:
# Access each field in the row using its index
field1 = row[0]
field2 = row[1]
field3 = row[2]
# Print the values
print(field1, field2, field3)
|
In this example, we use the csv module to read a CSV file named data.csv. We open the file using the open() function and create a CSV reader object using the csv.reader() function. We then loop through each row in the CSV file and access the values of each field using its index. Finally, we print the values to the console.
Here is an example of how to write data to a CSV file in Python:
|
import csv
# Create a list of data
data = [
['John', 'Doe', '28'],
['Jane', 'Doe', '30'],
['Bob', 'Smith', '35']
]
# Open a new CSV file
with open('output.csv', 'w', newline='') as file:
# Create a CSV writer object
writer = csv.writer(file)
# Write each row of data to the CSV file
for row in data:
writer.writerow(row)
|
In this example, we create a list of data and then write it to a new CSV file named output.csv. We open the file using the open() function and create a CSV writer object using the csv.writer() function. We then loop through each row of data and write it to the CSV file using the writer.writerow() function. The newline='' argument is added to ensure that the output file doesn't have extra blank rows between rows of data.
There are many other methods and options available in the csv module, such as specifying a different delimiter or quote character, using a dictionary to write data to a CSV file, and more. You can refer to the official Python documentation for more information on working with CSV files in Python.