我正在尝试将数据保存到csv文件中,但出现以下错误:
Traceback (most recent call last):
File "H:\Yr11 Computer Science\New Lessons\Lesson 26-27\song.py", line 13, in <module>
csv_file = ([song, + ',' + artist + genre])
TypeError: bad operand type for unary +: 'str'#
此处提供代码:
import csv
print('*Welcome to Music*')
Choice = input('Do you want to *add* a song, print a *list* or *output* to a text file? ')
Choice = Choice.lower()
if Choice == 'add':
song = input ("Please enter a song name: ")
artist = input ("Please enter the Artist: ")
genre = input ("Please enter the Genre: ")
songs = open('songs.csv', 'a')
csv_file = ([song, + ',' + artist + genre])
songs.write(csv_file)
database.close()
elif Choice == 'list':
()
感谢任何帮助,谢谢
答案 0 :(得分:1)
在其他人提出的建议的基础上,并根据我认为您需要的内容,我认为您应该为追加添加以下代码:
with open("songs.csv", "a") as fa:
line = song + "," + artist + "," + genre + "\n"
fa.write(line)
这可确保在执行附加操作后关闭文件对象,并且还会在较早的行下方附加较新的行,从而使生成的CSV结构化。
答案 1 :(得分:0)
这仅与错误消息TypeError: bad operand type for unary +: 'str'
有关。是从线开始的
csv_file = ([song, + ',' + artist + genre])
,表示python无法理解+ ','
。如果您删除第一个+
,您将摆脱该特定错误消息。也许还有更多...
python会抱怨,因为您尝试使用list
作为文件名。也许你想要
csv_file = song + ',' + artist + genre
答案 2 :(得分:0)
似乎song
之后不需要逗号:
csv_file = ([song, + ',' + artist + genre])
相反,请尝试:
csv_file = ([song + ',' + artist + genre])
编辑:,如@hiro主角所建议-您还可以简化整行并在不带括号的情况下编写。