@zealtric
2021-08-20T03:02:06.000000Z
字数 2040
阅读 152
python
import csv
Python 的 CSV模块的使用方法,包括,reader, writer, DictReader, DictWriter.register_dialect
http://www.cnblogs.com/sislcb/archive/2008/12/15/1355481.html
但是对于tsv文件,不知道为什么不需要再次导入tsv模块(甚至好像没有这种模块),,可能csv模块涵盖了不止csv文件,还有tsv文件
with open('CityTemps.csv', 'rU') as my_temps_file:
my_temps_reader = csv.DictReader(my_temps_file)
例子
import csv
all_temps = []
with open('CityTemps.csv', 'rU') as my_temps_file:
my_temps_reader = csv.DictReader(my_temps_file)
for row in my_temps_reader:
all_temps.append(row['temp'])
print all_temps
- DictReader:读取csv的,生成一个字典类型的返回
- row就是随便命名的一个循环儿子,不需要做声明,随便写就行。而对于‘temp’,则是CityTemps.csv里面的一个属性
例子
import csv
attributes = ['city', 'state', 'lat', 'lng', 'temp', 'region', 'coastal']
temps_regions_file = open('OurTempsRegions.csv','w')
csvwriter = csv.DictWriter(temps_regions_file, delimiter=',', fieldnames=attributes)
csvwriter.writeheader()
cities = []
with open('CityTemps.csv', 'rU') as citytemps_file:
for row in csv.DictReader(citytemps_file):
cities.append(row)
regions = []
with open('Regions.tsv', 'rU') as regions_file:
for row in csv.DictReader(regions_file, delimiter='\t'):
regions.append(row)
for city in cities:
for region in regions:
if region['state'] == city['state']:
city.update(region)
csvwriter.writerow(city)
break
temps_regions_file.close()
这里呢,首先OurTempsRegions.csv是一个空文档,然后CityTemps.csv和Regions.tsv是两个有内容的文档。
CityTemps.csv里面有'city', 'state', 'lat', 'lng', 'temp'五个属性
Regions.tsv里面有'state', 'region', 'coastal'三个属性
这里将这两个文件信息合并,写入到OurTempsRegions.csv中去
rU或Ua以读方式打开,同时提供通用换行符支持
http://www.360doc.com/content/14/0425/12/16044571_372066859.shtml
# iterate through index, and typecast each element
for index in range(len(all_temps)):
all_temps[index] = int(all_temps[index])
# all cities with 'ville' in them
for city_info in all_temps_regions:
if 'ville' in city_info['city']:
print 'City: {}, State: {}, Temp: {}'.format(city_info['city'], city_info['state'], city_info['temp'])
输出
City: Jacksonville, State: Florida, Temp: 45
City: Louisville, State: Kentucky, Temp: 27
City: Nashville, State: Tennessee, Temp: 31