Search code examples
pythonstringoperation

Separating a string by the first occurrence of a separator


I just got into python very recently and now I'm practicing by (what I imagine to be rather simple, but challenging enough for me) creating small tools to sort files into folders.

So far it has been going pretty well, but now I've encountered a problem:

My files are in the following format: myAsset_prefix1_prefix2_prettyName.ext ; (i.e. Tiger_texture_spec_brightOrange.png)

myAsset always has a different length since it's dependent on name.

I want to sort every file of the same asset ( "myAsset_" tag) in a separate folder.

The copying to a separate folder etc is no challenge but.. I don't want to update an array by hand every time I create/receive a new asset. So instead of using the startswith operation and make it run through a list, I'd like to build that array when my script runs, by making the script look at the name of the file and store everything up to and including the first "_" in a variable/array.

Is that possible?


Solution

  • I think you want the glob module. This allows you to list the files that match a certain format.

    For example:

    for filename in glob.glob(*.ext):
        asset_tag = filename.split(" ")[0]