Python: 重命名文件夹的前 5 个文件

Python: Renaming first 5 files of a folder

我不知道这是否可以完成,但是有没有办法只重命名文件夹中的前 5 个文件?我知道我可以使用 os.listdir() 或 os.walk() 遍历整个文件夹,但我只需要重命名前 5 个文件。我可以使用 Regex 来匹配文件,但问题是还有其他文件匹配相同的 Regex。有没有人有什么建议? 文件名采用 "Test Run 1 4-29-2016 2 07 56 PM" 的形式。

您可以限制来自 listdir 的结果:

os.listdir(os.curdir)[:5]

glob.glob 将允许您使用通配符过滤文件

glob.glob(pathname) Return a possibly-empty list of path names that match pathname, which must be a string containing a path specification. pathname can be either absolute (like /usr/src/Python-1.5/Makefile) or relative (like ../../Tools//.gif), and can contain shell-style wildcards. Broken symlinks are included in the results (as in the shell). No tilde expansion is done, but *, ?, and character ranges expressed with [] will be correctly matched.

glob.glob('*.gif')[:5]