簡體   English   中英

如何使用Python遍歷Excel文件

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

我想添加一個空列表“ 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']

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

希望此片段可以對您有所幫助。

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

如果您使用的是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()

您現在可以遍歷此列表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM