Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I move files to a specific folder using only the first 4 letters

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)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading