如何将列表的片段写入我的.csv文件?

时间:2016-05-14 08:25:17

标签: python python-3.x csv

在我的计算机科学课 - 9年级计算机科学中,我们正在使用用户自己输入的信息写入.csv文件。我使用的代码应该解释我尝试做的事情,但我很困惑,因为.csv文件中没有输出。我认为这是因为我尝试从列表中获取信息并将其放入.csv文件中,我可能还没有正确完成,但任何帮助都会很棒。另外,不要使用比我在这里所做的更高级的东西来完全改变代码,因为我将大部分的知识用于编写代码。

import csv
import os

n = 10

names = list()
timeonstage = list()
moneypayed = list()

menu = input('Would you like to make a new table (New) or edit an existing    one(Edit)?')
if menu == 'New':


    for i in range(0, n):
        names.append(input('Please enter the name of the artist you would like to add: '))
    print(names)

    for i in range(0, n):
        timeonstage.append(input('Please enter how much time the actor is on     stage for: '))
    print(timeonstage)

    for i in range(0, n):
         moneypayed.append(input('Please enter how much money is being payed to    the actor: '))
    print(moneypayed)

    os.remove('MFP.csv')

    f = open('MFP.csv', 'a+')

    write1 = names[0]+','+timeonstage[0]+','+moneypayed[0]
    write2 = names[1]+','+timeonstage[1]+','+moneypayed[1]
    write3 = names[2]+','+timeonstage[2]+','+moneypayed[2]
    write4 = names[3]+','+timeonstage[3]+','+moneypayed[3]
    write5 = names[4]+','+timeonstage[4]+','+moneypayed[4]
    write6 = names[5]+','+timeonstage[5]+','+moneypayed[5]
    write7 = names[6]+','+timeonstage[6]+','+moneypayed[6]
    write8 = names[7]+','+timeonstage[7]+','+moneypayed[7]
    write9 = names[8]+','+timeonstage[8]+','+moneypayed[8]
    write10 = names[9]+','+timeonstage[9]+','+moneypayed[9]
    columns = 'Name of artist:'+','+'Artists time on stage:'+','+'Money        being payed:'

    f.write(str(columns))
    f.write('\n')
    f.write(str(write1))
    f.write('\n')
    f.write(str(write2))
    f.write('\n')
    f.write(str(write3))
    f.write('\n')
    f.write(str(write4))
    f.write('\n')
    f.write(str(write5))
    f.write('\n')
    f.write(str(write6))
    f.write('\n')
    f.write(str(write7))
    f.write('\n')
    f.write(str(write8))
    f.write('\n')
    f.write(str(write9))
    f.write('\n')
    f.write(str(write10))
    f.write('\n')

1 个答案:

答案 0 :(得分:1)

当您完成编辑后,您在此处所做的并未关闭新的CSV文件,因此python不知道保存您的编辑内容。通过在代码末尾添加f.close(),可以轻松完成文件的关闭。

  

完成文件后,请调用f.close()将其关闭并释放   打开文件占用的任何系统资源。打电话后   f.close(),尝试使用文件对象将自动失败。

(来自https://docs.python.org/3.5/tutorial/inputoutput.html#methods-of-file-objects