如何编写字典和列表到CSV或蟒蛇的.xlsx

时间:2019-01-31 11:20:02

标签: python excel csv

新到SO和编程所以TIA的任何帮助。

我有城市及其对应国家的词典。 我有每个城市的经度和纬度列表(使用Selenium进行了刮除)。

在当前代码中,我只能将纬度和经度写入.csv文件。

反正我还能写字典键(城市)和相应的long_lat,所以我知道long_lat属于哪个城市吗?

代码:

import os, time, openpyxl, csv
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

#IMPORT EXCEL FILE
print('opening workbook...')
os.chdir('C:\\Users\\user1\\Documents')
wb = openpyxl.load_workbook('Data.xlsx')
sheet = wb['Missing']

d = {} #dictionary to contain city and corresponding country

#GRAB CITY AND COUNTRY FROM EXCEL
for row in range(2,5):
    country = sheet['B' + str(row)].value
    city = sheet['C' + str(row)].value

    d[city] = country

lat_long_list = [['-24.211531', ' 151.902298'], ['-20.269600', ' 148.720535'], ['-43.805199', ' 172.966995']]


with open('csvPrintTest.csv', 'w') as csv_file:
    writer = csv.writer(csv_file)
    for coOrdinate in lat_long_list:
        writer.writerow([coOrdinate])

print('Done')    

在Excel中打开csv时所需的输出:

City         LatLong

Agnes Waters  ['-24.211531', '151.902298']
Airlie Beach  ['-20.269600', ' 148.720535']
Akaroa        ['-43.805199', ' 172.966995']

2 个答案:

答案 0 :(得分:0)

假设您的sheet与您的lat_long_list同步,请创建list中的dict

lat_long_list = [['-24.211531', ' 151.902298'], ['-20.269600', ' 148.720535'], ['-43.805199', ' 172.966995']]

csv_data = []
for row in range(2,5):
    country = sheet['B' + str(row)].value
    city = sheet['C' + str(row)].value
    i = row - 2
    csv_data.append({'city':city, 
                     'country':country, 
                     'lat':lat_long_list[i][0], 
                     'long':lat_long_list[i][1]
                    })

fieldnames = ['city', 'country', 'lat', 'long']
header = {'city':'City', 'country':'Country', 'lat':'Lat', 'long':'Long'}

with open('csvPrintTest.csv', 'w') as csv_file:
    writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
    writer.writerow(header)
    writer.writerows(csv_data)

答案 1 :(得分:0)

如果列表的顺序与其余数据的顺序相同,则可以轻松地将其添加到字典中,然后创建一个数据框,后跟df.to_csv('filename')。希望能帮助到你。如果序列与字典中其余列表的序列不同,请非常小心。