如何让os.listdir按顺序列出文件

时间:2018-03-06 19:43:33

标签: python

我想重命名目录中的所有文件。在Windows资源管理器中按名称排序时,它们按正确顺序显示:

Cue 001 - 002.mp3
...
Cue 001 - 010.mp3
Cue 001 - 011.mp3
...
Cue 001 - 020.mp3
Cue 001 - 021.mp3
...
Cue 001 - 0111.mp3
Cue 001 - 0112.mp3

到目前为止,我已经能够使用os.chdir将工作目录更改为包含目标文件的目录,并使用print (os.getcwd())进行确认。

import os
# Lets change working directory to the Python Rename Test folder
os.chdir(r'F:\My backup\Documents and Settings\user\My Documents\My         Music\The Commitments\The Commitments - Mustang Sally_Recursive\Backup\Python Rename Test')
# confirm working directory by printing it out
print (os.getcwd())
# loop over the files in the working directory and printing them out
for file in os.listdir(os.getcwd()):
    print (file)

这就是我得到的:

Cue 001 - 002.mp3
...
Cue 001 - 010.mp3
Cue 001 - 0100.mp3
Cue 001 - 0101.mp3
...

如何让os.listdir以正确的顺序打印文件?

2 个答案:

答案 0 :(得分:0)

我假设您希望文件按文件扩展名之前的数字排序。

import re

files = os.listdir(os.getcwd())
sorted_files = sorted(files,key=lambda x: int(re.sub(r'\D','',x.strip())[3:]))
print(sorted_files)

答案 1 :(得分:0)

如果您的文件的第一个数字超过100,此代码会按两个数字排序。

In[2]: import re
  ...: 
  ...: 
  ...: def sorted_by_nums(filenames):
  ...:     """Assuming filenames are in this format 'Cue 001 - 002.mp3'"""
  ...:     def by_nums(filename):
  ...:         *nums, _ = re.findall(r'\d+', filename)
  ...:         return [int(num) for num in nums]
  ...: 
  ...:     return sorted(filenames, key=by_nums)
  ...: 
In[3]: filenames = [
  ...:     'Cue 001 - 010.mp3',
  ...:     'Cue 001 - 011.mp3',
  ...:     'Cue 001 - 0112.mp3',
  ...:     'Cue 001 - 0111.mp3',
  ...:     'Cue 001 - 002.mp3',
  ...:     'Cue 001 - 020.mp3',
  ...:     'Cue 001 - 021.mp3'
  ...: ]
# you could replace `filenames` with `os.listdir(...)` below
In[4]: for file in sorted_by_nums(filenames):
  ...:     print(file)
  ...: 
Cue 001 - 002.mp3
Cue 001 - 010.mp3
Cue 001 - 011.mp3
Cue 001 - 020.mp3
Cue 001 - 021.mp3
Cue 001 - 0111.mp3
Cue 001 - 0112.mp3