I have a list splitting problem in Python

Question:

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.

Asked By: baumanager

||

Answers:

Probably what You want is .split() function: https://docs.python.org/3/library/stdtypes.html#str.split

Answered By: Aidas

Instead of using list(), use str.split(). To do this, you can’t use readlines(), as that returns a list of lines.

You’re looking for something like this:

filenew_content = playlist_file_new.read().split(",")

This takes the file object, gets a string containing it’s contents, and splits it into a list, using a comma as the separator.

Answered By: Morpheus636

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.

Answered By: 123

If you mean you want to turn list[str] into list[str, str, str…], you can use the str.split(str) method. See the following:

l = ["hello,world,this,is,a,list"]
new_l = l[0].split(",")
print(new_l)
>>> ["hello", "world", "this", "is", "a". "list"]
Answered By: Anonymous

The string.split(‘,’) method should work.
for example

# loop over all the lines in the file
for line in filenew.readlines():
    items = line.strip().split(',')
    # strip strips the line of leading and trailing whitespace. 
    # split returns a tuple of all the strings created by 
    # splitting at the given character.

    # loop over all the items in the line
    for item in items:
        # add them to the list
        filenew_content.append(item)

See also: Python documentation for strings

Answered By: Josh M
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.