将列表保存到.csv文件

时间:2017-09-20 12:33:05

标签: python-3.x csv nested export-to-csv

我创建了一个代码,用于打开.csv文件并使用用户输入将其过滤到新列表。我遇到的问题是将这个新列表正确保存到.csv文件中。

这是我的代码:

@author: Joakim

from pprint import pprint
import csv

with open ('Change_in_Unemployment_2008-2014.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')

next(readCSV)     #Removing header 

result = []
found = False
user_input = input("Please enter a full/partial NUTS code to filter by: ")
for row in readCSV:
    if row[0].startswith(user_input):
        result.append(row)
        found = True
if found == False:
    print("There are no registered NUTS codes containing your input.. Please try again")
if found == True:
    print("\n Successfully found ", len(result), "entries!""\n")

pprint (result)

#store data in a new csv file

Stored_path = "C:\data_STORED.csv"
file = open(Stored_path, 'w')
writer = csv.writer(file)
writer.writerow(["NUTS CODE", " Municipality", " value"])
for i in range(len(result)):
    new_row = result[i]
    NUTS_CODE = new_row[0]
    Municipality = new_row[1]
    Value = new_row[2]
    writer.writerow([NUTS_CODE, Municipality])






csvfile.close()

如果使用输入:PL运行我的代码,则获取此列表:

[['PL11', 'odzkie', '2.2'],
['PL12', 'Mazowieckie', '1.2'],
['PL21', 'Maopolskie', '2.9'],
['PL22', 'Slaskie', '2'],
['PL31', 'Lubelskie', '1.1'],
['PL32', 'Podkarpackie', '5.8'],
['PL33', 'Swietokrzyskie', '2.6'],
['PL34', 'Podlaskie', '2.7'],
['PL41', 'Wielkopolskie', '1.6'],
['PL42', 'Zachodniopomorskie', '-1.1'],
['PL43', 'Lubuskie', '1.8'],
['PL51', 'Dolnoslaskie', '0'],
['PL52', 'Opolskie', '1.3'],
['PL61', 'Kujawsko-Pomorskie', '1.6'],
['PL62', 'Warminsko-Mazurskie', '2.4'],
['PL63', 'Pomorskie', '3.1']]'

现在我想将它整齐地存储到一个新的.csv文件中,但是当我使用上面的代码时,我只会重复几个值。 我的错误是什么?

0 个答案:

没有答案