Search code examples
pythonstringfilenames

How do I read specific characters of filename in Python 2.7


Lets say I have a bunch of folders/files with a name like

    abc_06082018

where the numbers are the date it was created but they are different for each folder, however the abc_ stays the same for every name. How do I only read after the abc_ and up until 8 number in?

BTW: The folder is the current working directory of the python 2.7 program, so i'm using os.getcwd() and saving it to a variable most likely as a string. The idea is to get the date from the cwd and make a file in the cwd in the form of

    newfile_06082018.txt

where the numbers are taken from the name of the cwd Thank you!


Solution

  • The name of the folder is in a string - just use normal string manipulation! .partition() is your friend.

    folder = os.getcwd()
    
    absolute_folder = os.path.abspath(folder)
    only_folder_name = os.path.basename(absolute_folder)
    
    prefix, sep, date_suffix = only_folder_name.partition('_')
    filename = 'newfile_{date}.txt'.format(date=date_suffix)