[Tutor] Move files to a new directory with matching folder names
questions anon
questions.anon at gmail.com
Thu May 22 05:10:22 CEST 2014
Thank you for your response. I have created some sample folders and tried
your method but I receive an error:
IOError: [Errno 21] Is a directory: '/Data/test1/2011/01'
The script I use is:
destination_prefix="/Data/test/"
source_prefix="/Data/test1/"
for year in range(2011, 2012):
year = str(year)
for month in range(1, 13):
# convert to a string with leading 0 if needed
month = "%02d" % month
source = os.path.join(source_prefix, year, month)
destination = os.path.join(destination_prefix, year, month)
shutil.copy(source, destination)
On Thu, May 22, 2014 at 11:11 AM, Steven D'Aprano <steve at pearwood.info>wrote:
> On Thu, May 22, 2014 at 10:25:27AM +1000, questions anon wrote:
> > I have files contained separately in folders labelled by years and months
> > and I would like to copy them into another directory where they have
> > matching folder names of years and months.
> > I can do this for one folder at a time (see below) but I want it to be
> able
> > to go through all the folders (2002/01,2002/02.....2012/11,2012/12) and
> > copy files from one directory to another directory with matching subdir
> > names.
>
> You need a loop.
>
> Currently you do something like this:
>
>
> source="/Data/allclimatedata/2002/01"
> destination="/Data/rainfall/2002/01"
> copy files from source to destination
>
>
> The dumb way would be to manually list out every pair of directories:
>
>
> source="/Data/allclimatedata/2002/01"
> destination="/Data/rainfall/2002/01"
> copy files from source to destination
> source="/Data/allclimatedata/2002/02"
> destination="/Data/rainfall/2002/02"
> copy files from source to destination
> ... and so on, for 12 months per year and however many years you need
>
>
>
> The smart way is to get Python to do the work for you:
>
>
> source_prefix = "/Data/allclimatedata"
> destination_prefix = "/Data/rainfall"
> for year in range(2002, 2013):
> year = str(year)
> for month in range(1, 13):
> # convert to a string with leading 0 if needed
> month = "%02d" % month
> source = os.path.join(source_prefix, year, month)
> destination = os.path.join(destination_prefix, year, month)
> copy files from source to destination
>
>
>
>
> --
> Steven
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20140522/a0cd8feb/attachment.html>
More information about the Tutor
mailing list