python中csv文件的详细操作

在Python中,可以使用内置的csv模块来操作CSV文件。以下是一些常见的CSV文件操作示例:

1. 读取CSV文件:
import csv

with open('file.csv', 'r') as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)
2. 写入CSV文件:
import csv

data = [['Name', 'Age', 'City'],
        ['John', '25', 'New York'],
        ['Alice', '30', 'London'],
        ['Bob', '35', 'Paris']]

with open('file.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerows(data)
3. 读取特定列的数据:
import csv

with open('file.csv', 'r') as file:
    reader = csv.reader(file)
    for row in reader:
        name = row[0]
        age = row[1]
        print(name, age)
4. 写入特定列的数据:
import csv

data = [['Name', 'Age'],
        ['John', '25'],
        ['Alice', '30'],
        ['Bob', '35']]

with open('file.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    for row in data:
        writer.writerow(row)
这些示例演示了如何读取和写入CSV文件,以及如何访问特定列的数据。您可以根据您的需求进行适当的修改和扩展。希望对您有帮助!

你可能感兴趣的:(python笔记,python,开发语言)