想象一下这样的情况:你有一个文件夹,其中包含多种类型的文件,如txt、mp3等。你决定清理这些混乱,并以一种方式组织它们,使图像在一个文件夹中,歌曲在另一个文件夹中。您是否会按照文件类型移动它们,即移动次数=文件数量。不,我不会这么做:)。
这个任务可以通过编写python脚本来实现自动化,该脚本可以自动创建一个单独的目录,并将文件移动到各自的目的地。
请注意,您需要 安装Python 2 在你的系统上。该脚本使用了名为os的模块,该模块允许我们使用特定于os的功能。请注意,在完成这一切之前,您需要在系统上设置Python。为此,请遵循以下步骤:
1) 从这里下载Python; https://www.python.org/downloads/ (我更喜欢2.7,因为它是一个稳定的版本) 2) 安装它。 转到C:(windows所在的位置)并获取python文件夹的路径 (大概是C:Python27) 3) 转到我的电脑(或这台电脑),转到高级系统设置 ,在那里搜索变量路径,然后单击编辑。 4) 将出现一个带有路径的框,将光标滚动到已经存在的路径,直到结束并添加 ;C:Python27 (即;然后是C驱动器中python文件夹的路径)。 5) 单击保存或确定。在C:中创建一个名为Pyprog(或任何其他名称)的文件夹,我们将在这里存储所有python程序, 打开cmd并键入cd C:Pyprog 然后运行名为first的文件。py(每个python程序都有一个扩展名.py),首先运行python。皮耶。
Python代码 直接链接 – https://ide.geeksforgeeks.org/9bY2Mm
Python3
# Python program to organize files of a directory import os import sys import shutil # This function organizes contents of sourcePath into multiple # directories using the file types provided in extensionToDir def OrganizeDirectory(sourcePath, extensionToDir): if not os.path.exists(sourcePath): print ( "The source folder '" + sourcePath + "' does not exist!!" ) else : for file in os.listdir(sourcePath): file = os.path.join(sourcePath, file ) # Ignore if its a directory if os.path.isdir( file ): continue filename, fileExtension = os.path.splitext( file ) fileExtension = fileExtension[ 1 :] # If the file extension is present in the mapping if fileExtension in extensionToDir: # Store the corresponding directory name destinationName = extensionToDir[fileExtension] destinationPath = os.path.join(sourcePath, destinationName) # If the directory does not exist if not os.path.exists(destinationPath): print ( "Creating new directory for `" + fileExtension + "` files, named - `" + destinationName + "'!!" ) # Create a new directory os.makedirs(destinationPath) # Move the file shutil.move( file , destinationPath) def main(): if len (sys.argv) ! = 2 : print ( "Usage: <program> <source path directory>" ) return sourcePath = sys.argv[ 1 ] extensionToDir = {} extensionToDir[ "mp3" ] = "Songs" extensionToDir[ "jpg" ] = "Images" print ("") OrganizeDirectory(sourcePath, extensionToDir) if __name__ = = "__main__" : main() |
请注意,在上图中,在执行脚本时创建了两个名为Images和Songs的新文件夹,带有mps和jpg扩展名的文件现在位于所需的文件夹中
请注意,上述帖子中提到的路径是根据一个通用系统,您应该根据我们的要求更改路径并进行分类,但重要的一点是更改当前的工作目录,这是使用操作系统完成的。chdir()。此外,还可以添加更多关于不同文件类型的if语句。
关于作者:Ekta是Geeksforgeks上非常活跃的贡献者。目前在德里科技大学学习。她还为手机做了一个Chrome扩展 www.geeksquick。通用域名格式 随机练习MCQ。你可以通过电话联系到她 github。com/Ekta1994
如果你也想在这里展示你的博客,请参见 吉微博 在Geeksforgek上写客博。