Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

python csv文件处理

作者:无法言喻   发布日期:2025-05-15   浏览:40

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')

解释说明:

  1. 导入模块import csv 导入Python的内置模块csv,用于处理CSV文件。
  2. 读取CSV文件
    • read_csv 函数打开指定路径的CSV文件,并使用csv.reader读取每一行数据,然后打印出来。
  3. 写入CSV文件
    • write_csv 函数接受文件路径和要写入的数据列表,使用csv.writer将数据写入CSV文件。
  4. 示例数据:定义了一个包含表头和几行数据的二维列表data
  5. 调用函数:先调用write_csv将数据写入example.csv文件,再调用read_csv读取并打印文件内容。

上一篇:pythonprint用法

下一篇:python创建线程

大家都在看

python时间格式

python ord和chr

python list.pop

python的for i in range

npm config set python

python代码简单

python读取文件夹

python中turtle

python 输出时间

python中list代表什么

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站