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

暴雪

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

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')
认证机构

在这里完成的操作不会在CSV完成编辑后关闭新文件,因此python不知道保存您的编辑。通过将f.close()代码添加到代码末尾,可以轻松完成关闭文件的操作

处理完文件后,调用f.close()将其关闭并释放打开文件占用的所有系统资源。调用f.close()之后,尝试使用文件对象将自动失败。

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章