mardi 17 décembre 2019

Append the filename with part of string in directory in python

My folder structure is this way Root has multiple directories which has multiple files and I want particular pdf to be appended with part of string in directory.

Dir1 -> I_want_apple_in_file_name

Filename ->Fruit

Dir2 -> I_want_Orange_in_file_name

Filename ->Fruit

I want specific part of string which is in fixed position to appended after pdf filename. My output should be:

Dir1 -> I_want_apple_in_file_name

Filename ->Fruit_apple

Dir2 -> I_want_Orange_in_file_name

Filename ->Fruit_Orange

My code is like this:

    pattern ='Fruit_*.pdf'
    file_name = [ os.path.join(r, file) for r, d, f in os.walk(path) for file in f if  fnmatch.fnmatch(file,pattern) ]
    for file in file_name :
      head_tail = os.path.split(file)
      filematch = head_tail[1]
      directory_split = (head_tail[0])
      sec_head_tail =os.path.split(directory_split)
      str = [sec_head_tail[1] ] 

Now str has directory name. How to store directory name in string and get the position. I was thinking to rename or append the string as suffix in filename. I am a beginner in python.

Aucun commentaire:

Enregistrer un commentaire