0

I Have a folder with 150 pdf files. I also have a list of 200 names which correspond to a number of those pdf files. I.e. with the following format:

Mark: 100900, 890210, 1212012

Sam: 210102, 203101,

Matt: 123101, 120123, 123123, 123101

etc.

I would like to create subdirectories for all the names, and then make copies of the pdf files from the original folder into each of the subdirectories.

What I have now so far is create the directories, but now trying to figure out how to copy files from a seperate folder if there matches with the main list.

import itertools
 import os

 dirs = ["Mark","Sam","Matt","..."]

 for item in dirs:
     os.makedirs(item)
user1982011
  • 307
  • 1
  • 4
  • 12
  • Possible Duplicate question. Answer is at: http://stackoverflow.com/questions/123198/how-do-i-copy-a-file-in-python http://stackoverflow.com/questions/3397752/copy-multiple-files-in-python – Versatile May 28 '15 at 14:47
  • 1
    Do all the PDFs have the same naming format? – LampPost May 28 '15 at 14:47
  • What I am trying to figure out is how to copy a file if there is a match, it is not just how to copy a file. – user1982011 May 28 '15 at 14:48
  • The pdf files are variable in their names, some have numbers and others have words. – user1982011 May 28 '15 at 14:49
  • What version of python are you using? Python 2 or 3? Also. What operating system is this using/is this targeted for? This can affect the answers quite significantly – Dudemanword May 28 '15 at 14:53
  • Ah i see, I am using a MAC OS and Python 2.7 – user1982011 May 28 '15 at 14:59
  • please state a clear question or describe the expected outcome, the actual outcome and which part you think fails and how – knitti May 28 '15 at 15:34
  • The question is clear. I have a folder with files. I have a txt file which shows folder <> file relationships. I would like to copy files from the main directory to folder subdirectories. – user1982011 May 28 '15 at 16:42

1 Answers1

0

I would suggest you to use shutil, it is good for working with files in directories

And the code will look as follows:

 import shutil
 import os
 from os.path import exists
 from os import listdir

 nameslist = ["Mark: 100900, 890210, 1212012","Sam: 210102, 203101", "Matt: 123101, 120123, 123123, 123101"]

for item in nameslist: 
parts = item.split(': ')
names = parts[0]
numbers = parts[1].split(", ") #get lists from numbers
if not exists(names):  #create directories
    os.mkdir(names)

for f in listdir(os.getcwd()):  
    if f.endswith(".pdf"):
        if f.replace(".pdf",'') in numbers:
            shutil.copy(f, names)

Hope this helps.

If your .pdf files are not in the directory of your python file, replace os.getcwd() with path to that directory

KseniaK
  • 3
  • 2