Search code examples
pythonexport-to-csvpython-re

Using csv I want to select an random row with data and extract the data so S =songs and A = artist,repeat


My attempt bellow, can you help improve it, thanks in advance.

def Start():
    with open('Songs.csv') as Data #Call file
    Read = csv.reader(Data,delimiter=':', quotechar='|')#return tuple of songs and artists
    for row in Read :
        X = random.choice(row)#random selection
        Store = (','.join(X))#(Song,Artist)
        A = re.compile(‘,’)
        for s in finditer(Store):
            POS = s.start()#positional arg for slicing
            global Song
            Song = X[POS:]#song,
            global Artist
            Artist = X[:POS]#Artist
            print(Song)

Solution

  • After reading the heading i suppose you want to read a file line by line and split the line based on a delimiter. The following code can be helpful

    def Start():
    with open('Songs.csv') as f:
        line = f.readline()
        columns = line.split(':')
        #read columns list using index to get any values
    

    The code you provided isn't much helpful. I suggest to a description with the code.