【发布时间】:2020-04-01 18:34:40
【问题描述】:
使用整数文件名对文件进行排序。
- 我需要使用文件名中的整数根据文件名升序对Python中的文件进行排序. python3中的sort函数将文件名排序为1,11,12,13,......,19,2,21 ,22.....等等。
- 有些文件的文件名有例外,例如,有些文件被命名为 1a.htm、3a.htm、4a.htm。我想忽略这些文件,并且不想将这些文件包含在我最终排序的文件列表中。 The files and folders I want to sort
正常排序问题:
import bs4
from bs4 import BeautifulSoup
import os,glob
root='data_sample_gnc/'
for path, subdirs, files in os.walk(root):
for file in sorted(files):
if(file.endswith('.htm')):
print(file)
输出 1.htm 10.htm 11.htm 12.htm 13.htm 14.htm 15.htm 16.htm 17.htm 18.htm 19.htm 1a.htm 2.htm 20.htm 21.htm 22.htm 23.htm 24.htm 25.htm 26.htm 27.htm 28.htm 29.htm 3.htm 30.htm
异常问题:
import bs4
from bs4 import BeautifulSoup
import os,glob
root='data_sample_gnc/'
for path, subdirs, files in os.walk(root):
sorted_files=sorted(files, key=lambda x: int(x.split('.')[0]))
for file in sorted_files:
print(file)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-45-2881098be594> in <module>
5 root='data_sample_gnc/'
6 for path, subdirs, files in os.walk(root):
----> 7 sorted_files=sorted(files, key=lambda x: int(x.split('.')[0]))
8 for file in sorted_files:
9 print(file)
<ipython-input-45-2881098be594> in <lambda>(x)
5 root='data_sample_gnc/'
6 for path, subdirs, files in os.walk(root):
----> 7 sorted_files=sorted(files, key=lambda x: int(x.split('.')[0]))
8 for file in sorted_files:
9 print(file)
ValueError: invalid literal for int() with base 10: '1a'
提前感谢您的帮助。 :) xD
【问题讨论】:
-
分割点并使用if条件isalnum作为第一个元素
标签: python python-3.x file sorting