如何将列表中的数据写入我的.csv文件?

2024-09-30 00:36:39 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的计算机科学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')

Tags: 文件csvtheto代码inforinput
1条回答
网友
1楼 · 发布于 2024-09-30 00:36:39

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

When you’re done with a file, call f.close() to close it and free up any system resources taken up by the open file. After calling f.close(), attempts to use the file object will automatically fail.

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

相关问题 更多 >

    热门问题