3 回答

TA贡献1783条经验 获得超4个赞
在python中使用os模块和shutil模块
import os
import shutil
你可以准备一个包含匹配模式喜欢的列表
match_pattern=['99574404682','99574449752','99581722007']
然后使用 os.listdir() 获取包含源目录中文件名的列表
files_in_source_dir=os.listdir(source_directory_path)
最后复制匹配的文件
for file in files_in_source_dir:
if file.split('.')[0] in match_pattern: #using split('.')[0] to get filename without extend name
shutil.copyfile(source_directory_path+file,target_directory_path+file)

TA贡献1846条经验 获得超7个赞
您可以使用shutil.copy()将文件从源复制到目标。
from shutil import copy
from os import listdir
from os import makedirs
from os.path import abspath
from os.path import exists
from os.path import splitext
filenames = {'99574404682', '99574449752', '99581722007'}
src_path = # your files
dest_path = # where you want to put them
# make the destination if it doesn't exist
if not exists(dest_path):
makedirs(dest_path)
# go over each file in src_path
for file in listdir(src_path):
# If underscore in file
if "_" in file:
prefix, *_ = file.split("_")
# otherwise treat as normal file
else:
prefix, _ = splitext(file)
# only copy if prefix exist in above set
if prefix in filenames:
copy(abspath(file), dest_path)
这会导致以下文件dest_path:
99574404682_0.jpg
99574404682_1.jpg
99574449752.jpg
99581722007.gif
我不是真正的 bash 专家,但你可以尝试这样的事情:
#!/bin/bash
declare -a arr=("99574404682" "99574449752" "99581722007")
## Example directories, you can change these
src_path="$PWD/*"
dest_path="$PWD/src"
if [ ! -d "$dest_path" ]; then
mkdir $dest_path
fi
for f1 in $src_path; do
filename=$(basename $f1)
prefix="${filename%.*}"
IFS='_' read -r -a array <<< $prefix
for f2 in "${arr[@]}"; do
if [ "${array[0]}" == "$f2" ]; then
cp $f1 $dest_path
fi
done
done

TA贡献2016条经验 获得超9个赞
您可以遍历两个列表,根据startswith条件从一个列表中获取项目:
files_lst = ['99574404682_0.jpg', '99574404682_1.jpg', '99574437307_0.gif', '99574437307_1.gif', '99574437307_2.gif', '99574449752.jpg', '99574457597.jpg', '99581722007.gif']
lst = [99574404682, 99574449752, 99581722007]
for x in files_lst:
for y in lst:
if x.startswith(str(y)):
print(x)
# 99574404682_0.jpg
# 99574404682_1.jpg
# 99574449752.jpg
# 99581722007.gif
这将获取所有以 中提供的数字开头的文件lst。
添加回答
举报