python-CSV文件和JSON数据

1、读取csv文件 csv.reader()函数

csv模块是python自带的,可以直接导入它

代码如下:

import csv

exampleFile=open('example.csv')

exampleReader=csv.reader(exampleFile) #读取csv文件

exampleData=list(exampleReader) #返回List列表

exampleData

1)访问特定行和列的值:exampleData[row][col]

exampleData[0][0]

2)如果读取大型的CSV文件,使用for循环遍历

代码如下:

import csv

exampleFile=open('example.csv')

exampleReader=csv.reader(exampleFile)

for row in exampleReader:

print('Row # '+str(exampleReader.line_num)+' '+str(row))

2、写入csv csv.writer()函数

代码如下:

import row

outputFile=open('output.csv','w',newline='')

outputWriter=csv.writer(outputFile)        #创建写入文件对象

outputWriter.writerow(['spam','eggs','bacon','ham'])        #写入行数据

outputFile.close()

3、分隔符        delimiter和lineterminator

代码如下:

import csv

csvFile=open('example.csv','w',newline='')

csvWriter=csv.writer(csvFile,delimiter='\t',lineterminator='\n\n')        #设置分隔符

csvWriter.writerow(['apples','oranges','eggs'])

csvFile.close()

4、读取JSON        loads()函数

代码如下:

import json

stringOfJsonData='{"name":"Zophie","isCat":true}'

jsonDataAsPythonValue=json.loads(stringOfJsonData)        #读取json数据转换为python的值

jsonDataAsPythonValue

5、写出JSON        dumps()函数

import json

pythonValue={isCat':True,'name':'Zophie'}

stringOfJsonData=json.dumps(pythonValue)        #python的值转换为json数据

stringOfJsonData

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值