赞
踩
import json import csv import os def csv_process(filepath): with open(filepath,mode='r',encoding='utf-8',newline='') as f: #此处读取到的数据是将每行数据当做列表返回的 reader = csv.reader(f) for row in reader: #此时输出的是一行行的列表 # print(row) print('+'.join(row)) def json_process(filepath): with open(filepath,mode='r',encoding='utf-8') as f: city_list = json.load(f) print(city_list) def main(): filepath = input('请输入文件名称:') name,index = os.path.splitext(filepath) if index == '.json': json_process(filepath) elif index == '.csv': csv_process(filepath) if __name__ == '__main__': main()
这是csv文件
time_point,aqi,quality,primary_pollutant,position_name,area,station_code,pm2_5,pm2_5_24h 2017-07-29T14:00:00Z,44,优,,天坛,北京,1004A,24,30 2017-07-29T14:00:00Z,46,优,,农展馆,北京,1005A,28,38 2017-07-29T14:00:00Z,47,优,,万寿西宫,北京,1001A,32,33 2017-07-29T14:00:00Z,50,优,,古城,北京,1012A,35,27 2017-07-29T14:00:00Z,54,良,细颗粒物(PM2.5),海淀区万柳,北京,1007A,38,28 2017-07-29T14:00:00Z,57,良,细颗粒物(PM2.5),东四,北京,1003A,40,36 2017-07-29T14:00:00Z,58,良,细颗粒物(PM2.5),官园,北京,1006A,41,32 2017-07-29T14:00:00Z,58,良,"颗粒物(PM2.5),颗粒物(PM10)",,北京,,40,29 2017-07-29T14:00:00Z,60,良,细颗粒物(PM2.5),奥体中心,北京,1011A,43,32 2017-07-29T14:00:00Z,63,良,颗粒物(PM10),定陵,北京,1002A,37,20 2017-07-29T14:00:00Z,77,良,颗粒物(PM10),昌平镇,北京,1010A,46,20 2017-07-29T14:00:00Z,80,良,臭氧1小时,怀柔镇,北京,1009A,48,21 2017-07-29T14:00:00Z,102,轻度污染,细颗粒物(PM2.5),顺义新城,北京,1008A,76,38
reader = csv.reader(f) 此时reader返回的值是csv文件中每行的列表,将每行读取的值作为列表返回
for row in reader:
print(row)
此时运行程序打印出来的row如下:
['time_point', 'aqi', 'quality', 'primary_pollutant', 'position_name', 'area', 'station_code', 'pm2_5', 'pm2_5_24h'] ['2017-07-29T14:00:00Z', '44', '优', '', '天坛', '北京', '1004A', '24', '30'] ['2017-07-29T14:00:00Z', '46', '优', '', '农展馆', '北京', '1005A', '28', '38'] ['2017-07-29T14:00:00Z', '47', '优', '', '万寿西宫', '北京', '1001A', '32', '33']为一个个列表
如果我们想用另外一种方式展示可以用如下方法:
print(', '.join(row))
展示如下:
time_point,aqi,quality,primary_pollutant,position_name,area,station_code,pm2_5,pm2_5_24h 2017-07-29T14:00:00Z,44,优,,天坛,北京,1004A,24,30 2017-07-29T14:00:00Z,46,优,,农展馆,北京,1005A,28,38 2017-07-29T14:00:00Z,47,优,,万寿西宫,北京,1001A,32,33 2017-07-29T14:00:00Z,50,优,,古城,北京,1012A,35,27
上面的用法举个简单例子:
l = ['a','b','c','d']
print('+'.join(l))
输出结果为:
[a+b+c+d]
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。