2017-08-28 67 views
0

是相當新的編程和我需要一種方法來從一個函數中增加了輸入數據,並把它添加到CSV文件中如何添加到CSV文件,從不同的功能在Python

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文件中。 對不起,如果這個問題格式不正確。 謝謝

回答

0

我不確定csv.reader的具體細節,但使用標準open(「text.csv」),你需要添加參數'a'(即打開(text.csv,' a')。write(new_song,「,」,something_else,「\ n」)以附加模式打開它,而不是默認讀取模式(或明確的'r')模式。注意不要使用'w'因爲這會在寫入之前擦除文件清潔

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