脚本运行后未将数据写入csv文件

时间:2019-03-29 01:10:35

标签: python python-3.x csv

我是python的新手,在将数据输出到csv文件时遇到了一些麻烦。该脚本将运行,但是该文件为空白,没有任何数据。

#!/usr/bin/env python3

import os
import smtplib
import csv

os.system('clear')

class CreateList(object):
    def add_items(self):
        shop_list = []
        print("Lets create a shopping list for you..\n")
        print("Please enter DONE when you have all the items needed for your shopping list.")
        while True:
            add_item = input("> ")
            if add_item == 'DONE':
                break
                shop_list.append(add_item)
                print("Here is your current shopping list:")
        csv = open('shoplist.csv', 'w')
        for item in shop_list:
            print(item)
            csv.write(item + '\n')
        csv.close()

c = CreateList()
c.add_items()

2 个答案:

答案 0 :(得分:0)

缺少else。您的input未向shop_list附加任何内容,因此没有任何内容写入文件。

import os
import smtplib
import csv

os.system('clear')

class CreateList(object):
    def add_items(self):
        shop_list = []
        print("Lets create a shopping list for you..\n")
        print("Please enter DONE when you have all the items needed for your shopping list.")
        while True:
            add_item = input("> ")
            if add_item == 'DONE':
                break
            else: # <<< missing
                shop_list.append(add_item)
                print("Here is your current shopping list:")
        csv = open('shoplist.csv', 'w')
        for item in shop_list:
            print(item)
            csv.write(item + '\n')
        csv.close()

c = CreateList()
c.add_items()

答案 1 :(得分:0)

您可能会有一些缩进。这是相同的脚本,但第19行和第20行中的一些缩进已删除。

#!/usr/bin/env python3

import os
import smtplib
import csv

os.system('clear')

class CreateList(object):
    def add_items(self):
        shop_list = []
        print("Lets create a shopping list for you..\n")
        print("Please enter DONE when you have all the items needed for your shopping list.")
        while True:
            add_item = input("> ")
            if add_item == 'DONE':
                break
            shop_list.append(add_item)
        print("Here is your current shopping list:")
        csv = open('shoplist.csv', 'w')
        for item in shop_list:
            print(item)
            csv.write(item + '\n')
        csv.close()

c = CreateList()
c.add_items()