简体   繁体   English

如何根据文件名将文件分类到相应的文件夹中?

[英]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)文件名示例: 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).我必须根据基金名称(上例中的 BREIT)将每个文件保存在正确的文件夹中。 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).但是,我们提供 50 多种资金,因此每次我从门户网站保存文档时都需要点击几次才能到达正确的文件夹(我每天保存数百个)。

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.解决方案:我需要使用 Python 编写一个解决方案,使我能够将所有文档保存到一个通用文件夹中,然后运行代码,根据文件中的基金名称将通用文件夹中的所有文件分类到各自的文件夹中姓名。

Any tips on how to get started with this would be greatly appreciated.任何有关如何开始使用此功能的提示将不胜感激。 Thanks.谢谢。

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.您可以使用os.listdir(path)来完成此操作。

  2. Loop over the files.循环遍历文件。

  3. Break a filename into components.将文件名分解为组件。 If the components are separated by - , you can use the string.split() method.如果组件由-分隔,则可以使用string.split()方法。

    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 useshutil.move() to move a file.您可以使用shutil.move()来移动文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM