0

I need to create a copy of a directory tree called "caritemscopy" where all files, instead of being in directories named after years, rather have the year as part of the filename, and the year directories are entirely absent

My directory currently looks like this

After coding my directory should looks like this

Mukyuu
  • 6,436
  • 8
  • 40
  • 59
Jojo
  • 11
  • Hello Jojo. You are not the only person with this homework. The question at https://stackoverflow.com/questions/59081909/rename-files-to-instead-being-in-sub-directories-have-the-year-as-part-of-the-f/59082549#59082549 is written with more clarity. – Charles Merriam Nov 28 '19 at 06:08

1 Answers1

0

It will list all directory files in path, then rename it and save all files at path and remove the empty directory.

import os


path = 'path_of_folder/F26/'

files = []

# r=root, d=directories, f = files

for r, d, f in os.walk(path):

    for file in f:
        if '.txt' in file:
            files.append(os.path.join(r, file))

for f in files:
    src = f.split('/')
    os.rename(f, path + src[-2]+'-'+src[-1])
    if not os.listdir(path+src[-2]):
        os.rmdir(path+src[-2])
    else:
        pass
Sachin Singh
  • 607
  • 4
  • 22