在Python中搜索带有扩展名的文件并复制到目录?
我对 Python 很陌生,正在尝试创建一个基本的备份程序,它允许我在计算机的整个主驱动器中搜索特定扩展名的文件(在本例中为 .doc),并且然后复制到预定目录(因为程序将从 USB 运行)。我已经掌握了一些基本的 I/O 命令,但在这方面遇到了相当大的困难。
有时间的人可以帮我解决这个问题吗?
感谢您的宝贵时间,
利亚姆.
I'm quite new to Python, and am attempting to create a basic backup program, that'll allow me to search for files of a certain extension (in this case, .doc), throughout the entire home drive of a computer, and then copy to a predetermined directory (as the program will be run from a USB). I've got a handle on some of the basic I/O commands, but am having a fair bit of difficulty with this.
Would anyone with the time be able to help me out with this?
Thanks for your time,
Liam.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要探索文件系统,您可以尝试 os.walk。它将递归地跟踪一个目录,在每个目录中生成文件和目录的列表。
例如,给定如下的目录结构:
此代码:
会生成如下内容:
然后您可以循环结果并编译要复制的文件列表。
对于复制文件,
shutil
包具有copy
,它仅采用 src/dest 文件路径。有关更多信息,请参阅文档: http://docs.python.org/library/shutil.html编辑
更有用的文件搜索内容包括:
glob
包:顾名思义,glob 样式文件匹配(*.txt、. 等)。我不相信这支持递归搜索。在此示例中,如果我执行glob('foo/*.doc')
,我将得到['foo/file2.doc']
的结果。fnmatch
包中的fnmatch
可以对字符串进行 glob 样式模式匹配。示例fnmatch('foo.txt', '*.txt')
将返回True
To explore the filesystem, you can try
os.walk
. It will recursively follow a directory yielding a list of files and dirs in each dir.For example, given a directory structure like this:
This code:
Would produce something like this:
You could then loop over the results and compile a list of files to copy.
For copying files, the
shutil
package hascopy
which just takes src/dest file paths. For more information, see the docs: http://docs.python.org/library/shutil.htmlEdit
More helpful file searching things include:
glob
package: As the name suggests, glob style file matching (*.txt, ., etc). I don't believe this supports recursive searching though. In this example, if I doglob('foo/*.doc')
, I would get the result of['foo/file2.doc']
.fnmatch
from thefnmatch
package can do glob style pattern matching against strings. Examplefnmatch('foo.txt', '*.txt')
Would returnTrue