如果在名为“file”的列表中找到文件,我将尝试将当前目录中的文件从当前目录移到当前目录中名为'python‘的目录。结果,名为'1245‘的文件将保留在同一个目录中。我试图使用fnmatch来匹配模式,以便可以移动所有以其名称包含123的文件。
import fnmatch
import os
import shutil
list_of_files_in_directory = ['1234', '1245', '1236', 'abc']
file = ['123', 'abc']
for f in os.listdir('.'):
if fnmatch.fnmatch(f, file):
shutil.move(f, 'python')这会引发以下错误: TypeError:预期的str、字节或os.PathLike对象,而不是列表
for f in os.listdir('.'):
if fnmatch.fnmatch(f, file+'*'):
shutil.move(f, 'python')这引发以下错误TypeError:只能将列表(而不是"str")连接到列表中
发布于 2022-03-14 12:21:16
file是一个列表,不能将其作为模式传递给fnmatch。
我猜你想要的是
for f in os.listdir('.'):
if any(fnmatch.fnmatch(f, pat+'*') for pat in file):
shutil.move(f, 'python')尽管可以说,file可能应该重命名为类似于patterns的东西。
https://stackoverflow.com/questions/71467470
复制相似问题