保存CSV文件内容的数据结构可以使用二维数组或列表。以下是使用Python代码示例:
import csv
# 二维数组
data = [['Name', 'Age', 'City'],
['John Doe', '30', 'New York'],
['Jane Smith', '25', 'San Francisco'],
['Bob Johnson', '35', 'Chicago']]
# 将数据保存到CSV文件
filename = 'data.csv'
with open(filename, 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerows(data)
# 利用CSV模块读取CSV文件内容
with open(filename, 'r') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
print(row)
# 列表
data = [['Name', 'Age', 'City'],
['John Doe', '30', 'New York'],
['Jane Smith', '25', 'San Francisco'],
['Bob Johnson', '35', 'Chicago']]
# 将数据保存到CSV文件
filename = 'data.csv'
with open(filename, 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
for row in data:
writer.writerow(row)
# 利用CSV模块读取CSV文件内容
with open(filename, 'r') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
print(row)
以上代码示例演示了如何使用二维数组或列表保存数据,并使用csv模块将数据写入CSV文件,以及如何读取CSV文件内容。
下一篇:保存CSV文件中的信息到文本