pythonos.path

Split pathname in python


I'm trying to rename a filename with python. the thing is, the filename has a specific amount of characters, 48 to be exactly, and i need to split this name into some variables, like split the file name into 10 characters, then into 20, then 16 and finally into 2.

ex. from 111111111122222222222222222222333333333333333344.txt to 22222222222222222244.txt

for file in os.listdir(folder):
    file_name, file_ext = os.path.splitext(file)

now, how could be split the file_name into those variables?


Solution

  • You can split via simple indexing I think, but don't see any pattern to split at those nos though... maybe try this then...

    file = "111111111122222222222222222222333333333333333344.txt"
    file_name = file[11:31] + file[-6:-4]
    file_ext = file[-4:]
    
    print(file_name)
    print(file_ext)
    
    # Output
    2222222222222222222344
    .txt