gpt4 book ai didi

Python 根据名称 move 文件

转载 作者:行者123 更新时间:2023-12-02 04:12:11 25 4
gpt4 key购买 nike

为了表扬,我当前正在使用的代码来自 cji 的回复,here.

我试图以递归方式从源文件夹中提取所有文件,并将它们 move 到文件名前五个字符的文件夹中 0:5

我的代码如下:

import os
import shutil

srcpath = "SOURCE"
srcfiles = os.listdir(srcpath)

destpath = "DESTINATION"

# extract the three letters from filenames and filter out duplicates
destdirs = list(set([filename[0:5] for filename in srcfiles]))


def create(dirname, destpath):
full_path = os.path.join(destpath, dirname)
os.mkdir(full_path)
return full_path

def move(filename, dirpath):
shutil.move(os.path.join(srcpath, filename)
,dirpath)

# create destination directories and store their names along with full paths
targets = [(folder, create(folder, destpath)) for folder in destdirs]

for dirname, full_path in targets:
for filename in srcfiles:
if dirname == filename[0:5]:
move(filename, full_path)

现在,更改 srcfiles = os.listdir(srcpath)destdirs = list(set([filename[0:5] for filename in srcfiles])) < strong>使用下面的代码获取一个变量中的路径和另一个变量中文件名的前五个字符。

srcfiles = []
destdirs = []

for root, subFolders, files in os.walk(srcpath):
for file in files:
srcfiles.append(os.path.join(root,file))
for name in files:
destdirs.append(list(set([name[0:5] for file in srcfiles])))

我将如何修改原始代码来使用它......或者如果有人对我将如何去做这件事有更好的想法。谢谢。

最佳答案

我无法真正轻松地测试它,但我认为这段代码应该可以工作:

import os
import shutil

srcpath = "SOURCE"
destpath = "DESTINATION"

for root, subFolders, files in os.walk(srcpath):
for file in files:
subFolder = os.path.join(destpath, file[:5])
if not os.path.isdir(subFolder):
os.makedirs(subFolder)
shutil.move(os.path.join(root, file), subFolder)

关于Python 根据名称 move 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36090884/

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