I am currently doing an apprenticeship as an IT specialist and only have to move files in Python to a specific folder based on the first 4 letters. All letters and numbers after the first 4 digits must be ignored. I hope you can help me here. The files have different extensions, e.g. .txt, .bat, .doc
import os
import shutil
from glob import glob
file_source = r'C:\Users\SHall\OneDrive\Desktop\Test'
file_destination = r'D:\BTLD'
get_files = os.listdir(file_source)
for BLTD*.txt in get_files:
os.replace(file_source,file_destination)
shutil.move(source,destination)
CodePudding user response:
This should do what you need. I'm using pathlib for path manipulation instead of os and glob (same thing really).
import pathlib
import shutil
source_dir = pathlib.Path('./path/to/source')
target_dir = pathlib.Path('./path/to/target')
for p in source_dir.glob('BTLD*.*'):
shutil.move(p, target_dir / p.name)
Edit: Automatically organize all files in folders starting with the first 4 letters of the file name. This is basic and I have only tested on some simple cases.
import pathlib
import shutil
source_dir = pathlib.Path('./path/to/source')
key_set = set()
for p in source_dir.glob('*.*'):
key_set.add(p.stem[:4])
target_dir_root = pathlib.Path('./path/to/target_root')
for k in key_set:
target_dir = target_dir_root / k
target_dir.mkdir(exists_ok=True) # Make directories as needed
for p in source_dir.glob(k '*.*'):
shutil.move(p, target_dir / p.name)