My task was to create a playlist with the title,artist and length and genre but the titles had to be sorted alphabetically i tried to sort out my song title column but it isnt working at all. Here's my code:
songs=open("songs.csv","w")
song_record="song title"+","+"artist"+","+"track length"+","+"genre"
songs.write(str(song_record)+"\n"+"\n")
print("Welcome! Please choose 5 songs per genre")
for i in range (3):
songtitle=str(input("What is the song called"))
artists=str(input("Who sung the song ( the main person)"))
length=str(input("In seconds, how long is the song- 1 min= 60 seconds"))
genree=str(input("What genre is this song"))
song_record=songtitle+","+artists+","+length+","+genree
songs.write(str(song_record)+"\n")
songs.write("\n")
songs.close()
songs=open("songs.csv","a+")
csv1=csv.reader(songs,delimiter=",")
sort=sorted(csv1,key=operator.itemgetter(0))
print(sort)
songs.close()
Instead of using csv.reader, use pandas.read_csv and then use sort_values function to sort the values.
import pandas as pd
df=pd.read_csv("songs.csv")
df=df.sort_values(['songtitle'], ascending=[True])
You can set ascending as False if you wish to.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.