【问题标题】:Read files sequentially in order [duplicate]按顺序读取文件[重复]
【发布时间】:2014-02-12 21:08:53
【问题描述】:

我在一个文件夹中有许多文件,它们的名称遵循约定:

0.1.txt, 0.15.txt, 0.2.txt, 0.25.txt, 0.3.txt, ...

我需要一一阅读并操作其中的数据。目前我使用以下命令打开每个文件:

import os
# This is the path where all the files are stored.
folder path = '/home/user/some_folder/'
# Open one of the files,
for data_file in os.listdir(folder_path):
    ...

不幸的是,这会以没有特定顺序读取文件(不确定如何选择它们),我需要从文件名最小编号的文件开始读取它们,然后是编号较大的文件,依此类推,直到最后一个。

【问题讨论】:

  • 您需要使用自然排序对文件进行排序。

标签: python file-io


【解决方案1】:

使用sorted() 的简单示例返回一个新的排序列表。

import os
# This is the path where all the files are stored.
folder_path = 'c:\\'
# Open one of the files,
for data_file in sorted(os.listdir(folder_path)):
    print data_file

您可以在Docs阅读更多内容

编辑以进行自然排序:

如果您正在寻找自然排序,您可以看到 @unutbu 的 post 这个很棒

【讨论】:

  • 您需要小心对字符串进行排序。排序['1','2','10'] 将返回['1','10','2']
  • @wnnmaw 我接受评论查看编辑。
  • 谢谢@KobiK,工作就像一个魅力!
  • Pypi natsort 为我编号为 .png 的文件工作。
猜你喜欢
  • 1970-01-01
  • 2021-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-25
相关资源
最近更新 更多