简体   繁体   English

如何使用Python遍历Excel文件

[英]How to iterate through an excel file with Python

I would like to append an empty list "city_names" and add all the names of a city in order from an excel file I have imported. 我想添加一个空列表“ 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']

I am not sure why it doesn't work. 我不确定为什么它不起作用。 The filename is 'cities'. 文件名是“城市”。

Hope this snippet may help you. 希望此片段可以对您有所帮助。

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

If you are using panads: 如果您使用的是panad:

import pandas as pd

filePath = 'cities.xlsx'  #your path to cities 
df = pandas.read_excel(filePath) #df = pandas.read_csv(filePath) if your file is in CSV format
city_names = df['city'].tolist()

You can now iterate through this list. 您现在可以遍历此列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM