python实现文件排序,文件名中含有英文和数字
时间: 2024-02-27 17:55:28 浏览: 253
可以使用Python内置的sorted()函数进行排序,排序时需要自定义排序规则。
假设要按照文件名中的数字进行排序,可以使用正则表达式提取数字作为排序依据。具体实现步骤如下:
1. 使用os模块获取文件列表
```python
import os
# 获取指定目录下的所有文件
files = os.listdir('/path/to/dir')
```
2. 使用正则表达式提取文件名中的数字
```python
import re
def extract_number(filename):
# 匹配文件名中的数字
match = re.search(r'\d+', filename)
if match:
return int(match.group())
else:
return -1 # 如果文件名中不含数字,则返回-1
# 测试提取函数
print(extract_number('file1.txt')) # 输出1
print(extract_number('file2.txt')) # 输出2
print(extract_number('file.txt')) # 输出-1
```
3. 使用sorted()函数进行排序
```python
sorted_files = sorted(files, key=extract_number)
```
完整代码示例:
```python
import os
import re
def extract_number(filename):
# 匹配文件名中的数字
match = re.search(r'\d+', filename)
if match:
return int(match.group())
else:
return -1 # 如果文件名中不含数字,则返回-1
# 获取指定目录下的所有文件
files = os.listdir('/path/to/dir')
# 按文件名中的数字排序
sorted_files = sorted(files, key=extract_number)
# 输出排序结果
for filename in sorted_files:
print(filename)
```
注意:以上代码只能按照文件名中的数字进行排序,如果要按照其他规则进行排序,需要修改extract_number()函数中的正则表达式。
阅读全文
相关推荐


















