Avatar of delic8te
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 :)
Python

Avatar of undefined
Last Comment
RichieHindle

8/22/2022 - Mon
RichieHindle

Given a directory structure like this:

c:\temp\ee\input
c:\temp\ee\output\invoices
c:\temp\ee\output\other

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.
FILES = [
    ['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)
delic8te

ASKER
thanks - but can u explain the for loop code to me - thanks
ASKER CERTIFIED SOLUTION
RichieHindle

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
or
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