首页 > 解决方案 > 如何使用 Python 遍历 excel 文件

问题描述

我想附加一个空列表“city_names”,并从我导入的 excel 文件中按顺序添加一个城市的所有名称。

city_names = []
for city in cities["City"]:
print("city")
print(city_names)`

should give me this result:
['Buenos Aires',
 'Toronto',
 'Pyeongchang',
 'Marakesh',
 'Albuquerque',
 'Los Cabos',
 'Greenville',
 'Archipelago Sea',
 'Walla Walla Valley',
 'Salina Island',
 'Solta',
 'Iguazu Falls']

我不确定为什么它不起作用。文件名是“城市”。

标签: pythonjupyter-notebook

解决方案


希望这个片段可以帮助你。

import xlrd

workbook = xlrd.open_workbook('Cities.xlsx') # put your filename
worksheet = workbook.sheet_by_name('Cities') # put sheet name

cities=[c.value for c in worksheet.col(0)] # expecting cities are in first column

推荐阅读