美文网首页
csv文件操作

csv文件操作

作者: 第六九书 | 来源:发表于2020-03-28 11:58 被阅读0次

一、需要的库

需要导入csv库
import csv

二、读取文件并将文件赋值到列表

with open(filename) as file:
    '''将文件打开,并赋值到file中'''
    reader = csv.reader(file) # 从file中读取文件至列表变量reader中。
    header_row = next(file) # 从变量中读取第一行做为文件头。然后再返回文件中的下一行。此时再读取reader将只从第二行读起。

三、查看文件头

# enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据索引的序号,一般用在 for 循环当中。
for index , column_header in enumerate(header):
    print(index,column_header)

enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据索引的序号,一般用在 for 循环当中。其语法如下:
enumerate(sequence, [start=0])

sequence -- 一个序列、迭代器或其他支持迭代对象。
start --序号起始位置。

例:seasons = ['Spring', 'Summer', 'Fall', 'Winter'],那么enumerate(seasons)输出的就是:0, 'Spring'、1, 'Summer'、2, 'Fall'、3, 'Winter'。而enumerate(seasons,start=1)输出的就是:1, 'Spring'、2, 'Summer'、3, 'Fall'、4, 'Winter'。

四、读取指定的列数据

根据前面的表头,获取数据的列序号。然后分别读取指定列的数据。

dates = []
for row in reader:
    date = int(row[1]) # 读取第二列数据(序号是1,因为是从0开始的),并转换为整型数据,浮点数用float()。
    dates.append(date)

五、读取行数据

dates = reader[1] #读取第一行数据。若转换为整型数据,则是int(),浮点数则是float()。

六、实例

读取csv文件中的部分列数据,并绘制图表

# 来源于教材,非原创。
import csv
import matplotlib.pyplot as plt
from datetime import datetime

filename = 'sitka_weather_2014.csv'
with open(filename) as f:
    reader = csv.reader(f)
    header_row = next(reader)

    dates,highs,lows = [],[],[]
    for row in reader:
        date = datetime.strptime(row[0],'%Y-%m-%d')
        dates.append(date)
        high = int(row[1])
        highs.append(high)
        low = int(row[3])
        lows.append(low)

fig = plt.figure(dpi=128,figsize=(10,6))
plt.rcParams['font.family'] = ['STFangsong']
plt.plot(dates,highs,c='r')
plt.plot(dates,lows,c='b')
plt.fill_between(dates,highs,lows,facecolor='yellow',alpha=0.3)
plt.title('阿拉斯加锡特卡日最高及最低气温统计表(2014年)')
plt.ylabel('温度(F)',fontsize=16)
plt.tick_params(axis='both',which='major',labelsize=12)
plt.show()

相关文章

网友评论

      本文标题:csv文件操作

      本文链接:https://www.haomeiwen.com/subject/arsjuhtx.html