Python Forum
Append root directory folder and subdirectory to filename
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Append root directory folder and subdirectory to filename
#3
(Aug-04-2020, 08:02 PM)bowlofred Wrote: In your rename, you're asking for only the final component of the path path.split(dirpath)[-1]

If you want all the components, then you'll need to grab them without the [-1] restriction. Probably just join all the components with "_" to turn it into a string.

Thank you for responding to my question. I am still struggling with this. I took out the [-1] restriction:

import os
from os import walk, path, rename
import mimetypes

for dirpath, _, files in walk('dir/test2'):
    for f in files:
    	if mimetypes.guess_type(f)[0] == 'text/plain':
        	rename(path.join(dirpath, f), path.join(dirpath, path.split(dirpath) + '_' + f))
And I got the following error:

Output:
File "filename2.py", line 8, in <module> rename(path.join(dirpath, f), path.join(dirpath, path.split(dirpath) + '_' + f)) TypeError: can only concatenate tuple (not "str") to tuple
Reply


Messages In This Thread
RE: Append root directory folder and subdirectory to filename - by glittergirl - Aug-04-2020, 09:44 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Compare folder A and subfolder B and display files that are in folder A but not in su Melcu54 3 643 Jan-05-2024, 05:16 PM
Last Post: Pedroski55
  delete all files and subdirectory from a main folder mg24 7 1,706 Oct-28-2022, 07:55 AM
Last Post: ibreeden
  Append files and add column with last part of each filename NiKirk 0 2,663 Feb-04-2022, 07:35 AM
Last Post: NiKirk
  Compare filename with folder name and copy matching files into a particular folder shantanu97 2 4,597 Dec-18-2021, 09:32 PM
Last Post: Larz60+
  Move file from one folder to another folder with timestamp added end of file shantanu97 0 2,531 Mar-22-2021, 10:59 AM
Last Post: shantanu97
  How to skip a folder directory in a loop mfkzolo 2 12,752 Nov-18-2020, 07:56 AM
Last Post: mfkzolo
  Python Cut/Copy paste file from folder to another folder rdDrp 4 5,184 Aug-19-2020, 12:40 PM
Last Post: rdDrp
  Cant Append a word in a line to a list err "str obj has no attribute append Sutsro 2 2,654 Apr-22-2020, 01:01 PM
Last Post: deanhystad
  How to change directory to any folder where python is not installed ? firashelou 4 2,685 Apr-03-2020, 02:43 PM
Last Post: firashelou
  Python 2.7 Import error. Directory and filename conflict petcoo00 2 2,439 Feb-02-2020, 08:46 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020