TommyTripod
TommyTripod

Reputation: 31

How to sort files into corresponding folders based on file name?

Example of a file name: 7777777 - John Doe - BREIT - 1027 (Acct # - Client Name - Fund Name - Form Type)

Problem: One of the more repetitive aspects of my job is saving down documents that are submitted to our document portal. I must save each document down in the correct folder based on fund name (BREIT in the example above). However, we offer 50+ funds, so it takes several clicks to get to the correct folder each time I save a document from the portal (I save hundreds per day).

Solution: I need to code a solution using Python that will enable me to save all docs down to a general folder and then run code that will sort all of the files in the general folder into their respective folders based on the fund name within the file name.

Any tips on how to get started with this would be greatly appreciated. Thanks.

Upvotes: 0

Views: 944

Answers (1)

Nick ODell
Nick ODell

Reputation: 25210

You can break this task up into some smaller steps:

  1. Listing the contents of a directory (or folder.) You have some input directory with the files you want to sort. You want to get a list of files in that directory. You can use os.listdir(path) to accomplish this.

  2. Loop over the files.

  3. Break a filename into components. If the components are separated by -, you can use the string.split() method.

    Example:

    >>> s = '7777777 - John Doe - BREIT - 1027'
    >>> s.split('-')
    ['7777777 ', ' John Doe ', ' BREIT ', ' 1027']
    
  4. Find the destination directory. As I understand it, this is just the name of the fund.

  5. Move the file. You can use shutil.move() to move a file.

Upvotes: 1

Related Questions