Python学习笔记(十二)——处理CSV文件和JSON数据

CSV

Reader对象

>>> import csv
>>> exampleFile = open('example.csv')
>>> exampleReader = csv.reader(exampleFile)
>>> exampleReader
<_csv.reader object at 0x00000267463ECBA8>
>>> exampleData = list(exampleReader)
>>> exampleData
[['4/5/2014 13:34', 'Apples', '73'], ['4/5/2014 3:41', 'Cherries', '85'], ['4/6/2014 12:46', 'Pears', '14'], ['4/8/2014 8:59', 'Oranges', '52'], ['4/10/2014 2:07', 'Apples', '152'], ['4/10/2014 18:10', 'Bananas', '23'], ['4/10/2014 2:40', 'Strawberries', '98']]
>>> exampleData[0][0]
'4/5/2014 13:34'

在for循环中,从Reader对象读取数据

>>> import csv
>>> exampleReader = csv.reader(open('example.csv'))
>>> for row in exampleReader:
    print('Row #'+ str(exampleReader.line_num) + '' +str(row))


Row #1['4/5/2014 13:34', 'Apples', '73']
Row #2['4/5/2014 3:41', 'Cherries', '85']
Row #3['4/6/2014 12:46', 'Pears', '14']
Row #4['4/8/2014 8:59', 'Oranges', '52']
Row #5['4/10/2014 2:07', 'Apples', '152']
Row #6['4/10/2014 18:10', 'Bananas', '23']
Row #7['4/10/2014 2:40', 'Strawberries', '98']

Write对象

>>> import csv
>>> csvFile = open('output.csv','w',newline='')
>>> csvWrite = csv.writer(csvFile)
>>> csvWrite.writerow(['spam','eggs','bacon','ham'])
21
>>> csvWrite.writerow(['hello,world!','eggs','bacon','ham'])
31
>>> csvWrite.writerow([1,2,3.1415926,4])               
17
>>> csvFile.close()

这里写图片描述

delimiter 和 lineterminator 关键字参数

>>> import csv             
>>> csvFile = open('output.tsv','w',newline='')            
>>> csvWrite = csv.writer(csvFile,delimiter='\t',lineterminator='\n\n')            
>>> csvWrite.writerow(['spam','eggs','bacon','ham'])               
21
>>> csvWrite.writerow(['hello','eggs','bacon','ham'])              
22
>>> csvFile.close()

Python学习笔记(十二)——处理CSV文件和JSON数据_第1张图片

小实验——从CSV文件中删除表头

#! python3
#removeCsvHeader.py - 
#Usage:
#
#Author : qmeng
#MailTo : [email protected]
#QQ     : 1163306125
#Blog   : http://blog.csdn.net/Mq_Go/
#Create : 2018-02-12 15:17:52
#Version: 1.0
#
import csv,os
#创建修改后的文件夹
os.makedirs('CSV2',exist_ok=True)
#遍历要修改的文件夹
for i in os.listdir('.\\CSV'):
    if not i.endswith('.csv'):
        continue
    print('Removing header from '+i +'...')
    csvPath = os.path.join('.\\CSV',i)
    csvRow = []
    #读取文件
    csvFile = open(csvPath)
    csvReader = csv.reader(csvFile)
    for Row in csvReader:
        if csvReader.line_num == 1:
            continue
        csvRow.append(Row)
    csvFile.close()

    #将csvRow中的内容生成新的CSV文件
    csvPath = os.path.join('.\\CSV2',i)
    csvFile = open(csvPath,'w',newline='')
    csvWriter = csv.writer(csvFile)
    for Row in csvRow:
        csvWriter.writerow(Row)
    csvFile.close()

JSON

JSON模块

用loads()函数读取JSON

>>> stringOfJsonData = '{"name":"Zophie","isCat":true,"miceCaught":0,"feLineIQ":null}'
>>> import json
>>> jsonDataAsPythonValue = json.loads(stringOfJsonData)
>>> jsonDataAsPythonValue
{'name': 'Zophie', 'isCat': True, 'miceCaught': 0, 'feLineIQ': None}

用dumps函数写出JSON

>>> jsonDataAsPythonValue
{'name': 'Zophie', 'isCat': True, 'miceCaught': 0, 'feLineIQ': None}
>>> import json
>>> josnString = json.dumps(jsonDataAsPythonValue)
>>> josnString
'{"name": "Zophie", "isCat": true, "miceCaught": 0, "feLineIQ": null}'

小实验——获取当前的天气数据

#! python3
#quickWeather.py - 
#Usage:
#
#Author : qmeng
#MailTo : [email protected]
#QQ     : 1163306125
#Blog   : http://blog.csdn.net/Mq_Go/
#Create : 2018-02-12 16:34:59
#Version: 1.0
#
import json,requests,sys
#输入查询地点
if len(sys.argv) < 2:
    print('Usage:quickWeather.py location')
    sys.exit()
location = ''.jion(sys.argv[1:])

#下载JSON数据
url = 'http://api.openweathermap.org/data/2.5/forecast/daily?q=%s&cnt3'%(location)
response = requests.get(url)
response.raise_for_status()

#加载JSON数据并打印天气
weatherData = json.loads(response.text)
w = weatherData['list']
print('Current weather in %s:'%(location))
print(w[0]['weather'][0]['main'],'-',w[0]['weather'][0]['description'])
print()
print('Tomorrow')
print(w[1]['weather'][0]['main'],'-',w[1]['weather'][0]['description'])
print()
print('Day After Tomorrow')
print(w[2]['weather'][0]['main'],'-',w[2]['weather'][0]['description'])
print()

你可能感兴趣的:(Python)