import csv
# 读取CSV文件示例
def read_csv(file_path):
with open(file_path, mode='r', newline='', encoding='utf-8') as file:
reader = csv.reader(file)
for row in reader:
print(row)
# 写入CSV文件示例
def write_csv(file_path, data):
with open(file_path, mode='w', newline='', encoding='utf-8') as file:
writer = csv.writer(file)
writer.writerows(data)
# 示例数据
data = [
['姓名', '年龄', '城市'],
['张三', '25', '北京'],
['李四', '30', '上海'],
['王五', '22', '广州']
]
# 写入CSV文件
write_csv('example.csv', data)
# 读取CSV文件
read_csv('example.csv')
import csv
导入Python的内置模块csv
,用于处理CSV文件。read_csv
函数打开指定路径的CSV文件,并使用csv.reader
读取每一行数据,然后打印出来。write_csv
函数接受文件路径和要写入的数据列表,使用csv.writer
将数据写入CSV文件。data
。write_csv
将数据写入example.csv
文件,再调用read_csv
读取并打印文件内容。上一篇:pythonprint用法
下一篇:python创建线程
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站