Avatar of delic8te
 asked on

Code for moving files from one location to another

I am having difficulties  in creating some code which does the following:

1) Searches through a table for files/path names  that exist
2) If they do exist, i.e. a path name exists, its takes the name of the file and moves it to another location - for e.g a file caled invoice.html which resided at c:mydocs\ now has to be copied and moved to a folder called c:\invoices.

Can anyone give me some example code that I can do that does this.
Thanks in advance

delic8te :)

Avatar of undefined
Last Comment

8/22/2022 - Mon

Given a directory structure like this:


where there are files called invoice.html and something.txt in c:\temp\ee\input, this will
move invoice.html to the 'invoices' directory and something.txt to the 'other' directory:

import os
from glob import glob
from os.path import join, split

# ROOT is where the input and output directories live.
ROOT = r'C:\temp\ee'

# The FILES table describes which files to find and where to put them.
# It allows wilcards, and defines a default rule for files that don't match.
    ['invoice*.html', 'invoices'],
    ['*', 'other'],

for pattern, destination in FILES:
    for pathname in glob(join(ROOT, 'input', pattern)):
        filename = split(pathname)[1]
        move_to = join(ROOT, 'output', destination, filename)
        print pathname, "->", move_to
        os.rename(pathname, move_to)

thanks - but can u explain the for loop code to me - thanks

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes