首页 > 解决方案 > 在python中根据文件名对文件进行排序

问题描述

使用整数文件名对文件进行排序。

  1. 我需要使用 filename 中的整数根据文件名升序对Python中的文件进行排序。python3中的sort函数将文件名排序为1,11,12,13 ,......, 19,2,21,22 ......等。
  2. 有一些文件的文件名例外,例如,一些文件被命名为 1a.htm、3a.htm、4a.htm。我想忽略这些文件,并且不想将这些文件包含在我最终排序的文件列表中。 我要排序的文件和文件夹

正常排序问题:


    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

标签: pythonpython-3.xfilesorting

解决方案


过滤非数字然后排序。

示例(使用文件字符串)

files = "1a.htm, 1b.htm, 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"

sorted_files = sorted(filter(lambda x: x.split('.')[0].isnumeric(), files.split()), key= lambda y: int(y.split('.')[0]))

print(sorted_files)

在上面的 files.split() 中,将字符串转换为文件列表(例如)

输出

['1.htm', '2.htm', '3.htm', '10.htm', '11.htm', '12.htm', '13.htm', '14.htm', '15.htm', '16.h.htm'tm', '17.htm', '18.htm', '19.htm', '20.htm', '21.htm', '22.htm', '23.htm', '24.htm', '25.htm'7.htm, '26.htm', '27.htm', '28.htm', '29.htm', '30.htm']

使用发布的示例(文件列表)

Posting 从以下位置获取文件列表:

for path, subdirs, files in os.walk(root):

files 已经 type ,所以我们不执行拆分来获取列表。

 sorted_files = sorted(filter(lambda x: x.split('.')[0].isnumeric(), files), key= lambda y: int(y.split('.')[0]))

# Above changed from files.split() to just files

推荐阅读