亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

腳本運行后數據未寫入 csv 文件

腳本運行后數據未寫入 csv 文件

呼喚遠方 2021-12-21 15:01:27
我是 python 新手,在將數據輸出到 csv 文件時遇到了一些問題。腳本運行但文件是空白的,創建時沒有數據。#!/usr/bin/env python3import osimport smtplibimport csvos.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 回答

?
有只小跳蛙

TA貢獻1824條經驗 獲得超8個贊

您可能只是有一些額外的縮進。這是相同的腳本,但在第 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()


查看完整回答
反對 回復 2021-12-21
?
開滿天機

TA貢獻1786條經驗 獲得超13個贊

有一個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()


查看完整回答
反對 回復 2021-12-21
  • 2 回答
  • 0 關注
  • 210 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號