I want to move all markdown (.md) files from one folder to another. The folder structure I have:
.
|-- Root11
| |-- FolderOne
| | |-- file1.md
| | |-- file1.txt
| | |-- file2.md
| | |-- file2.txt
| | |-- file3.md
| | |-- file3.txt
| | |-- file4.md
| | |-- file4.txt
| | |-- file5.md
| | `-- file5.txt
| `-- FolderTwo
|-- Root12
| |-- FolderOne
| | |-- file1.md
| | |-- file1.txt
| | |-- file2.md
| | |-- file2.txt
| | |-- file3.md
| | |-- file3.txt
| | |-- file4.md
| | |-- file4.txt
| | |-- file5.md
| | `-- file5.txt
| `-- FolderTwo
|-- Root13
| |-- FolderOne
| | |-- file1.md
| | |-- file1.txt
| | |-- file2.md
| | |-- file2.txt
| | |-- file3.md
| | |-- file3.txt
| | |-- file4.md
| | |-- file4.txt
| | |-- file5.md
| | `-- file5.txt
| `-- FolderTwo
|-- Root14
| |-- FolderOne
| | |-- file1.md
| | |-- file1.txt
| | |-- file2.md
| | |-- file2.txt
| | |-- file3.md
| | |-- file3.txt
| | |-- file4.md
| | |-- file4.txt
| | |-- file5.md
| | `-- file5.txt
| `-- FolderTwo
`-- Root15
|-- FolderOne
| |-- file1.md
| |-- file1.txt
| |-- file2.md
| |-- file2.txt
| |-- file3.md
| |-- file3.txt
| |-- file4.md
| |-- file4.txt
| |-- file5.md
| `-- file5.txt
`-- FolderTwo
15 directories, 50 files
In the above scenario, I want to move all markdown (.md) files from FolderOne
to FolderTwo
under folders Root11
to Root15
.
The current code I have in Python:
cur_path = os.getcwd()
outer_folder_path = f"{cur_path}\\root\\"
folder1 = "FolderOne"
folder2 = "FolderTwo"
root_dir, root_folders, _ = next(os.walk(outer_folder_path))
for root_folder in root_folders:
root_folder = os.path.join(root_dir, root_folder)
folder_path, folder_with_name_folders, _ = next(os.walk(root_folder))
for folder_with_name_folder in folder_with_name_folders:
if folder_with_name_folder == folder1:
check_this_folder = os.path.join(folder_path, folder_with_name_folder)
file_path, _, files = next(os.walk(check_this_folder))
for _file in files:
if _file.endswith(".md"):
input_file = os.path.join(file_path, _file)
ouput_file = input_file.replace(folder1, folder2)
os.rename(input_file, ouput_file)
pathlib
module would simplify things a lot for your task:for path in pathlib.Path(outer_folder_path).rglob('*.md'): ...
\$\endgroup\$