-2

I have a folder (folder_1) that consists of many different subfolders, these subfolders (subfolder_1, subfolder_2, etc etc) all consist of 1 csv file. I'd like to delete all subfolders, and just keep all csv files. Is there a way to achieve this without specifying all subfolders?

Maybe a way to make an exception for csv files using shutil?

Thanks in advance.

  • 2
    I don't think with `shutil` directly, but this should be trivial with `os.walk`. If pure Windows is not a strict requirement, GNU `find` can probably also do this. – tripleee May 03 '21 at 11:19
  • In Total Commander it is more convenient than in Python: Display all files in all subfolders by Ctrl+B, then select all of them (Ctrl+A) and move all them (F6) to an appropriate folder (maybe `folder_1` is your desired target folder). The Ctrl+B again, select all (now empty) folders and press the Delete key. – MarianD May 03 '21 at 11:38

1 Answers1

0

What you can do is:

  1. Loop over the subfolders. Check this post.
  2. Get the csv file(s) path. (replace the .txt to .csv from previous post)
  3. Use the shutil.move("path/to/current/file.foo", "path/to/new/destination/for/file.foo") to move the file on a higher level.
  4. use shutil.rmtree() to remove folder. (check here too)
George Sotiropoulos
  • 1,864
  • 1
  • 22
  • 32