我如何从python中的不同函数添加到csv文件

时间:2017-08-28 06:42:23

标签: python-3.x csv export-to-csv

对于编程来说相当新,我需要一种方法来从一个函数添加输入数据并将其添加到csv文件中

    def songlists():
        with open('songs.csv') as csvfile:
            songs = csv.reader(csvfile, delimiter = ',')
            x = [row for row in songs]
            return x

    def menu(x):
print("Songs to Learn 1.0 - ")
songlists()
print(len(x), "songs in list")
print("""Menu :
L - List songs
A - Add new song
C - Complete a song
Q - Quit""")
menuChoice = str(input('>>>'))
while menuChoice != "q":
    if menuChoice == "l":
        songlists()
        i = 0
        for row in x:
            name, artist, year, learnt = row
            print(str(i),'.', learnt, name, artist, "(", year, ")")
            i += 1
    elif menuChoice == "a":
        songlists()
        #want to be able to add to the csv file from here and be able to add the new name artists and year etc
        #print("??")
    elif menuChoice == "c":
        print("???")
    else:
        print("Invalid choice, Choose again")
    print("""Menu :
    L - List songs
    A - Add new song
    C - Complete a song
    Q - Quit""")
    menuChoice = str(input('>>>'))

我想做的是输入" a"用户在功能菜单()中提示他们添加名称和艺术家等,然后将其添加到歌曲列表功能中打开的csv文件中。 对不起,如果这个问题格式错误。 感谢

2 个答案:

答案 0 :(得分:0)

我不确定csv.reader的细节,但使用标准打开(" text.csv"),您需要添加参数' a&# 39; (即打开(text.csv,' a')。写(new_song,",",something_else," \ n")以便打开它附加模式,而不是默认读取(或明确的' r')模式。请注意不要使用' w'进行写入,因为这会在写入之前擦除文件。

答案 1 :(得分:0)

我写了一小段代码,可以帮助您解决问题。这并不完美,因为我会使用一个类而不是返回3个参数,但我认为这是一个好的开始,我们可以在以后改进它:

import csv

def getSong():
    name = raw_input("Artist's name: ")
    song = raw_input("Song's name: ")
    year = raw_input("Year: ")

    return name, song, year

def save(filename, name, song, year):
    with open(filename, 'a') as csvfile:
        writer = csv.writer(csvfile, delimiter=';')
        writer.writerow([name, song, year])

(name, song, year) = getSong()

save("output.csv", name, song, year)

HTH