【问题标题】:how do i add to a csv file from a different function in python如何从 python 中的不同函数添加到 csv 文件
【发布时间】:2017-08-28 06:42:23
【问题描述】:

我是编程新手,需要一种方法来从一个函数添加输入数据并将其添加到 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('>>>'))

我想做的是用户在功能 menu() 中输入“a”,它会提示他们添加名称和艺术家等,然后将其添加到在歌曲列表功能中打开的 csv 文件中. 抱歉,如果这个问题的格式不正确。 谢谢

【问题讨论】:

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


    【解决方案1】:

    我不确定 csv.reader 的具体细节,但使用标准 open("text.csv") 您需要添加参数 'a'(即 open(text.csv, 'a') .write(new_song, ",", something_else, "\n") 以便以附加模式打开它,而不是默认的读取(或显式'r')模式。注意不要使用'w'作为写入这将在写入之前清除文件。

    【讨论】:

      【解决方案2】:

      我写了一小段代码可以帮助您解决问题。这并不完美,因为我会使用一个类而不是返回 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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-07
        • 2018-10-27
        • 1970-01-01
        • 2011-04-28
        • 1970-01-01
        • 2020-11-06
        • 2019-03-19
        • 2017-03-11
        相关资源
        最近更新 更多