【问题标题】:Python Sort files with particular filename into specific folderPython将具有特定文件名的文件排序到特定文件夹中
【发布时间】:2022-08-05 23:34:14
【问题描述】:

示例环境

import os
import shutil
for filenames in os.getcwd():
   if filename.contains (\'pig\'):
        os.mkdir(\'Pig\')
        #move all the filenames which contain the name pig in it
        shutil.copy(filename-with-pig, Pig)
   if if filename.contains (\'dog\'):
        os.mkdir(\'Dog\')
        #move all the filenames which contain the name Dog in it
        shutil.copy(filename-with-dog, Dog)

如何在 Python 中做到这一点? 我已经尝试了一点,但是有很多错误

  • 这通常应该有效(尽管其中一些显然是伪代码,而不是实际代码)。如果您遇到错误,请发布它们。

标签: python python-3.x file operating-system shutil


【解决方案1】:

os.getcwd() 返回当前工作目录,您无法从中获取文件名。您必须使用os.listdir() 并且可以使用条件来选择文件并避开目录(如下所示)。

在循环中使用os.mkdir() 也会引发错误,因为您无法创建已经存在的目录。所以你应该检查它是否已经存在。

尝试这样的事情

import os
import shutil
cwd = os.getcwd()
files = (file for file in os.listdir(cwd) 
         if os.path.isfile(os.path.join(cwd, file)))
for filename in files:
   print(filename)
   if 'pig' in filename:
        if not os.path.exists('Pig'):
            os.mkdir('Pig')
        #move all the filenames which contain the name pig in it
        shutil.copy(filename, './Pig/'+filename)
   elif 'dog' in filename:
        if not os.path.exists('Dog'):
            os.mkdir('Dog')
        #move all the filenames which contain the name Dog in it
        shutil.copy(filename, './Dog/'+filename)

【讨论】: