python3提取并读取CSV数据
(2018-06-25 14:28:44)分类: Python3 |
阅读器对象从其停留的地方继续往下读取CSV文件,每次都自动返回当前所处位置的下一行。由于我们已经读取了文件头行,这个循环将从第二行开始---从这行开始包含的是实际数据。
highs_lows.py
import csv
#从文件中获取最高气温
filename = 'sitka_weather_07-2014.csv'
with open(filename) as f:
reader =
csv.reader(f)
header_row =
next(reader)
highs =
[]
for row in
reader:
highs.append(row[1])
print(highs)
输出:
['64', '71', '64', '59', '69', '62', '61', '55', '57', '61', '57', '59', '57', '61', '64', '61', '59', '63', '60', '57', '69', '63', '62', '59', '57', '57', '61', '59', '61', '61', '66']
将表示气温的字符串转换成数字
import csv
#从文件中获取最高气温
filename = 'sitka_weather_07-2014.csv'
with open(filename) as f:
reader =
csv.reader(f)
header_row =
next(reader)
highs =
[]
for row in
reader:
high = int(row[1])
highs.append(high)
print(highs)
输出:
[64, 71, 64, 59, 69, 62, 61, 55, 57, 61, 57, 59, 57, 61, 64, 61, 59, 63, 60, 57, 69, 63, 62, 59, 57, 57, 61, 59, 61, 61, 66]
highs_lows.py
import csv
#从文件中获取最高气温
filename = 'sitka_weather_07-2014.csv'
with open(filename) as f:
print(highs)
输出:
['64', '71', '64', '59', '69', '62', '61', '55', '57', '61', '57', '59', '57', '61', '64', '61', '59', '63', '60', '57', '69', '63', '62', '59', '57', '57', '61', '59', '61', '61', '66']
将表示气温的字符串转换成数字
import csv
#从文件中获取最高气温
filename = 'sitka_weather_07-2014.csv'
with open(filename) as f:
print(highs)
输出:
[64, 71, 64, 59, 69, 62, 61, 55, 57, 61, 57, 59, 57, 61, 64, 61, 59, 63, 60, 57, 69, 63, 62, 59, 57, 57, 61, 59, 61, 61, 66]