在python中以特定顺序读取文件

use*_*012 30 python file order-of-execution

假设我在一个文件夹中有三个文件:file9.txt,file10.txt和file11.txt,我想按照这个特定的顺序阅读它们.谁能帮我这个?

现在我正在使用代码

import glob, os
for infile in glob.glob(os.path.join( '*.txt')):
    print "Current File Being Processed is: " + infile
Run Code Online (Sandbox Code Playgroud)

它首先读取file10.txt然后是file11.txt,然后是file9.txt.

有人可以帮助我如何获得正确的订单吗?

Mar*_*ers 64

文件系统上的文件未排序.您可以使用以下sorted()函数自行对生成的文件名进行排序:

for infile in sorted(glob.glob('*.txt')):
    print "Current File Being Processed is: " + infile
Run Code Online (Sandbox Code Playgroud)

请注意,os.path.join您的代码中的调用是无操作的; 只有一个参数它不会做任何事情,但返回该参数不变.

请注意,您的文件将按字母顺序排序,10之前放置9.您可以使用自定义键功能来改进排序:

import re
numbers = re.compile(r'(\d+)')
def numericalSort(value):
    parts = numbers.split(value)
    parts[1::2] = map(int, parts[1::2])
    return parts

 for infile in sorted(glob.glob('*.txt'), key=numericalSort):
    print "Current File Being Processed is: " + infile
Run Code Online (Sandbox Code Playgroud)

numericalSort函数拆分文件名中的任何数字,将其转换为实际数字,并返回结果进行排序:

>>> files = ['file9.txt', 'file10.txt', 'file11.txt', '32foo9.txt', '32foo10.txt']
>>> sorted(files)
['32foo10.txt', '32foo9.txt', 'file10.txt', 'file11.txt', 'file9.txt']
>>> sorted(files, key=numericalSort)
['32foo9.txt', '32foo10.txt', 'file9.txt', 'file10.txt', 'file11.txt']
Run Code Online (Sandbox Code Playgroud)


hoc*_*chl 9

您可以将glob.glob( ... )表达式包装在sorted( ... )语句中,并对生成的文件列表进行排序.例:

for infile in sorted(glob.glob('*.txt')):
Run Code Online (Sandbox Code Playgroud)

您可以提供sorted比较函数,或者更好地使用key= ...参数为其提供用于排序的自定义键.

例:

有以下文件:

x/blub01.txt
x/blub02.txt
x/blub10.txt
x/blub03.txt
y/blub05.txt
Run Code Online (Sandbox Code Playgroud)

以下代码将生成以下输出:

for filename in sorted(glob.glob('[xy]/*.txt')):
        print filename
# x/blub01.txt
# x/blub02.txt
# x/blub03.txt
# x/blub10.txt
# y/blub05.txt
Run Code Online (Sandbox Code Playgroud)

现在有关键功能:

def key_func(x):
        return os.path.split(x)[-1]
for filename in sorted(glob.glob('[xy]/*.txt'), key=key_func):
        print filename
# x/blub01.txt
# x/blub02.txt
# x/blub03.txt
# y/blub05.txt
# x/blub10.txt
Run Code Online (Sandbox Code Playgroud)

编辑: 可能这个关键功能可以对您的文件进行排序:

pat=re.compile("(\d+)\D*$")
...
def key_func(x):
        mat=pat.search(os.path.split(x)[-1]) # match last group of digits
        if mat is None:
            return x
        return "{:>10}".format(mat.group(1)) # right align to 10 digits.
Run Code Online (Sandbox Code Playgroud)

它肯定可以改进,但我认为你明白了.没有数字的路径将保持不变,带有数字的路径将转换为10位宽的字符串并包含数字.