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='nn') #设置分隔符
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条)