Search code examples
pythonlistfilesplitreadfile

I have a list splitting problem in Python


I'm reading a file into a list. Now I want, that every after coma which I have in my list, there should be a new index. By now, everything is placed in index 0.

relevanted Code:

def add_playlist():
playlist_file_new =filedialog.askopenfilename(initialdir=f'C:/Users/{Playlist.username}/Music',filetypes=[('Playlistdateien','.txt')])
with open (playlist_file_new,'r') as filenew:
    filenew_content = list(filenew.readlines())
    print(filenew_content[0])

So, what do I have to do, so that after every comma there starts a new index ? Please help me and I thank you in advance. Also I'm sorry if this is a really basic question, I'm really new into programming.


Solution

  • I didn't try your code but I would do it like this:

    with open (playlist_file_new,'r') as filenew:
        filenew_content = filenew.read()
        filenew_content_list = filenew_content.split(",")
    

    That reads the complete data (please be careful with files bigger than your working memory (RAM)) of your file into the variable filenew_content. It is returned as a string. The string objects in Python have the method split(), where you can define a string where your bigger string should be splitted.