Skip to main content
 首页 » 编程设计

python之通过使用python检查字符串开头的数字来创建文件夹

2024年10月17日25jyk

我有一个字符串列表,其中包含如下文件

filename = [ '000101 FL - Project Title Page.DOC', 
 '014200 FL - References.DOC', 
 '095446 FL - Fabric-Wrapped Ceiling Panels.DOC', 
 '142113 FL - ELECTRIC TRACTION FREIGHT ELEVATORS.DOC'] 

我想检查是否存在名称由 Div + 每个字符串中的前两个数字组成的文件夹,例如本例中的 Div00、Div01、Div09、Div14。如果没有,我想创建这个文件夹。然后将文件的名称存储在该文件夹中。

在伪代码中我相信它会类似于

for file in filenames  
    if 'Div' + file[0][0] not a folder 
        make folder 'Div' + file[0][0] 
        add file to folder 
    else 
        add file to folder Div + file[0][0] 

会有多个文件以相同的两个数字开头,这就是为什么我想将它们分类到文件夹中。

如果您需要任何说明,请告诉我。

请您参考如下方法:

使用os.mkdir创建一个目录和shutil.copy2复制文件,

import os 
import shutil 
 
filenames = [ '000101 FL - Project Title Page.DOC'] 
 
for filename in filenames: 
    folder = 'Div' + filename[:2]       # 'Div00' 
 
    # Create the folder if doesn't exist 
    if not os.path.exists(folder): 
        os.makedirs(folder) 
 
    # Copy the file to `folder` 
    if os.path.isfile(filename): 
        shutil.copy2(filename, folder)  # metadata is copied as well