gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:12:18 27 4
gpt4 key购买 nike

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

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

关于python - 通过使用python检查字符串开头的数字来创建文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37622096/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com