python3读取和写入csv文件

本文介绍了如何使用Python3读取和写入CSV文件。首先展示了如何创建并读取CSV文件,通过`csv.reader`逐行读取内容,并获取特定列的数据。接着详细解释了如何写入CSV文件,使用`csv.writer`将数据写入文件。同时提到了`csv.DictWriter`对象的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

读取csv文件

一、创建一个csv文件

['city', 'password', 'day']
['1', '1', '1']
['2', '1', '1']
['3', '1', '1']
['4', '1', '1']
['5', '1', '1']
二、读取csv文件

import csv
#打开一个csv文件,模式为读取
csvfile = open('/Users/yanghui/Study/python/example.csv','r')
#定义一个变量,进行读取
readCSV = csv.reader(csvfile)
print(readCSV)
#分行打印
for row in readCSV:

    print(row)

#读取第一行第二个元素
readCSV = csv.reader(csvfile)
rows = [row for row in readCSV]

print(rows[0][1])

#获取第一行第二个元素
readCSV = csv.reader(csvfile)
for i,rows in enumerate(readCSV):
    if i == 0:
        row = rows

        print(rows[1])

#每列输出打印
readCSV = csv.reader(csvfile)
list1 = []
list2 = []
list3 = []
for row in readCSV:
    list1.append(row[0])
    list2.append(row[1])
    list3.append(row[2])
print(list1)
print(list2)
print(list3)

1 import csv
2 #打开文件,用with打开可以不用去特意关闭file了,python3不支持file()打开文件,只能用open()
3 with open("XXX.csv","r",encoding="utf-8") as csvfile:
4      #读取csv文件,返回的是迭代类型
5      read = csv.reader(csvfile)
6      for i in read:
7           print(i)

————————————————————————————————————————————————————————

写入csv文件

import csv
#打开一个csv文件,模式为写,如果没有该文件,则创建一个
with open('/Users/yanghui/Study/python/test.csv','a') as csvfile:
#定义一个写变量
    writeCSV = csv.writer(csvfile)
    writeCSV.writerow(['id','kebi','17'])

 

13.1.4. Writer Objects

Writer objects (DictWriter instances and objects returned by the writer() function) have the following public methods. A row must be a sequence of strings or numbers for Writer objects and a dictionary mapping fieldnames to strings or numbers (by passing them through str() first) for DictWriter objects. Note that complex numbers are written out surrounded by parens. This may cause some problems for other programs which read CSV files (assuming they support complex numbers at all).

csvwriter.writerow(row)

Write the row parameter to the writer’s file object, formatted according to the current dialect.

csvwriter.writerows(rows)

Write all elements in rows (an iterable of row objects as described above) to the writer’s file object, formatted according to the current dialect.

Writer objects have the following public attribute:

csvwriter.dialect

A read-only description of the dialect in use by the writer.

DictWriter objects have the following public method:

 

参考 https://docs.python.org/2/library/csv.html#writer-objects

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值