How can Python handle data in CSV files?
In Python, you can use the built-in csv module to manipulate data in CSV files. Here are some common operations:
- a tool used for reading and parsing CSV (comma-separated values) files
- the data file named data.csv
import csv
with open('data.csv', 'r') as file:
csv_reader = csv.reader(file)
for row in csv_reader:
print(row)
- a writer for CSV files
- information
- the file called output.csv
import csv
data = [['Name', 'Age', 'Country'],
['John', 25, 'USA'],
['Alice', 30, 'Canada']]
with open('output.csv', 'w', newline='') as file:
csv_writer = csv.writer(file)
csv_writer.writerows(data)
- a tool used for reading and parsing CSV (Comma-Separated Values) files
import csv
with open('data.csv', 'r') as file:
csv_reader = csv.reader(file)
data = []
for row in csv_reader:
data.append(row)
# 处理data中的数据
- Accessing and indexing CSV data: You can use indexes to access specific data in a CSV file. For example, if the first row of the CSV file is a header row, you can use indexes to access data from specific columns.
import csv
with open('data.csv', 'r') as file:
csv_reader = csv.reader(file)
for row in csv_reader:
name = row[0]
age = row[1]
country = row[2]
print(name, age, country)
These are some common methods for processing CSV file data, which you can modify and expand according to your specific needs.