将数据作为一系列以逗号分隔的值(CSV)写入文件 ,即可在文本文件中存储数据
1.分析CSV文件头import csv file_path='C:\Users\by\Desktop\python_work\unit\pcc- master\chapter_16\sitka_weather_07-2014.csv' #利用双反斜杠\分隔文件名 with open(file_path)as f: reader=csv.reader(f) header_row=next(reader) print(header_row)调用 csv.reader() , 并将前面存储的文件对象作为实参传递给它,从而创建一个与该文件相关联的阅读器(reader )对象 。我们将这个阅读器对象存储在 reader 中。 next函数将返回文件的下一行。 reader处理文件中以逗号分隔的第一行数据 2.打印文件头及其位置
--snip-- with open(file_path)as f: reader=csv.reader(f) header_row=next(reader) for index,column_header in enumerate(header_row): print(index,column_header)
enumerate获取元素索引及其值
3.提取并读取数据with open(file_path)as f: reader=csv.reader(f) header_row=next(reader) highs=[] for row in reader: highs.append(row[1]) print(highs)
可利用int将其转换为数字
with open(file_path)as f: reader=csv.reader(f) header_row=next(reader) highs=[] for row in reader: high=int(row[1]) highs.append(high) print(highs)4.绘制气温图表
import csv
from matplotlib import pyplot as plt
file_path='C:\Users\by\Desktop\python_work\unit\pcc-master\chapter_16\sitka_weather_07-2014.csv'
with open(file_path)as f:
reader=csv.reader(f)
header_row=next(reader)
highs=[]
for row in reader:
high=int(row[1])
highs.append(high)
fig=plt.figure(dpi=128,figsize=(10,6))
plt.plot(highs,c='red')
plt.title("Daily high temperatures,July 2014",fontsize=24)
plt.xlabel('',fontsize=16)
plt.ylabel('Temperature(F)',fontsize=16)
plt.tick_params(axis='both',which='major',labelsize=16)
plt.show()
5.模块datetime
使用模块datetime中的strptime()将字符串转换为表示日期的对象
from datetime import datetime
--snip--
first_date=datetime.strptime('2014-7-1','%Y-%m-%d')
print(first_date)
| 实参 | 含义 |
| %A | 星期的名称,如Monday |
| %B | 月份名,如January |
| %m | 用数字表示的月份(01~12) |
| %d | 用数字表示月份中的一天(01~31) |
| %Y | 四位的年份,如2015 |
| %y | 两位的年份,如15 |
| %H | 24 小时制的小时数(00~23) |
| %I | 12 小时制的小时数(01~12) |
| %p | am或pm |
| %M | 分钟数(00~59) |
| %S | 秒数(00~61) |
import csv
from datetime import datetime
from matplotlib import pyplot as plt
file_path='C:\Users\by\Desktop\python_work\unit\pcc-master\chapter_16\sitka_weather_07-2014.csv'
with open(file_path)as f:
reader=csv.reader(f)
header_row=next(reader)
#存储日期与温度
dates,highs=[],[]
for row in reader:
current_date=datetime.strptime(row[0],'%Y-%m-%d')
dates.append(current_date)
high=int(row[1])
highs.append(high)
fig=plt.figure(dpi=128,figsize=(10,6))
plt.plot(dates,highs,c='red')
plt.title("Daily high temperatures,July 2014",fontsize=24)
plt.xlabel('',fontsize=16)
#绘制斜体x轴标签,避免相互重叠
fig.autofmt_xdate()
plt.ylabel('Temperature(F)',fontsize=16)
plt.tick_params(axis='both',which='major',labelsize=16)
plt.show()
7.涵盖长时间
导入以下文件,获取全年温度
file_path='C:\Users\by\Desktop\python_work\unit\pcc-master\chapter_16\sitka_weather_2014.csv'8.再绘制一个数据
import csv
from datetime import datetime
from matplotlib import pyplot as plt
file_path='C:\Users\by\Desktop\python_work\unit\pcc-master\chapter_16\sitka_weather_2014.csv'
with open(file_path)as f:
reader=csv.reader(f)
header_row=next(reader)
dates,highs,lows=[],[],[]
for row in reader:
current_date=datetime.strptime(row[0],'%Y-%m-%d')
dates.append(current_date)
high=int(row[1])
highs.append(high)
low=int(row[3])
lows.append(low)
fig=plt.figure(dpi=128,figsize=(10,6))
plt.plot(dates,highs,c='red')
plt.plot(dates,lows,c='blue')
plt.title("Daily high and low temperatures,July 2014",fontsize=24)
plt.xlabel('',fontsize=16)
fig.autofmt_xdate()
plt.ylabel('Temperature(F)',fontsize=16)
plt.tick_params(axis='both',which='major',labelsize=16)
plt.show()
9.给图表区域着色
plt.plot(dates,highs,c='red',alpha=0.5) plt.plot(dates,lows,c='blue',alpha=0.5) plt.fill_between(dates,highs,lows,facecolor='blue',alpha=0.1)
alpha指定透明度。(从0到1逐渐不透明)
fill_between填充区域颜色
10.错误检查使用try-except避免遇到数据集异常时,代码无法运行
try:
current_date = datetime.strptime(row[0], "%Y-%m-%d")
high = int(row[1])
low = int(row[3])
except ValueError:
print(current_date, 'missing data')
else:
dates.append(current_date)
highs.append(high)
lows.append(low)



