Skip to content

Instantly share code, notes, and snippets.

@cessor
Created April 9, 2018 08:49
Show Gist options
  • Select an option

  • Save cessor/616ac685373f20df1c5a299c228d29be to your computer and use it in GitHub Desktop.

Select an option

Save cessor/616ac685373f20df1c5a299c228d29be to your computer and use it in GitHub Desktop.
Flatten a Directory by moving all files up one level.
import os
import shutil
ROOT = '.'
for dirpath, dirnames, filenames in os.walk(ROOT):
if dirpath == ROOT:
continue
for file in filenames:
source = os.path.join(dirpath, file)
destination = os.path.join(ROOT, file)
# Skip existing,
# First file wins
if os.path.exists(destination):
os.remove(source)
continue
# Move file up one level
shutil.move(source, ROOT)
# Delete Empty Folder
if not os.listdir(dirpath):
os.rmdir(dirpath)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment