首页 > 解决方案 > 使用 os.walk() 循环文件并打开它们

问题描述

我的主目录包含多个文件夹,每个文件夹内都有以下顺序的文件。

 7. ABCD.txt , 8. ABCD.txt, 9. ABCD.txt, 10. ABCD.txt , 11. ABCD.txt, 12.ABCD.txt etc. 

我想遍历所有文件夹并仅识别 .txt 文件。确定 .txt 文件后,我想按特定顺序阅读它们。

当我使用我的代码执行此操作时,它会按以下顺序读取它。

10. ABCD.txt , 11. ABCD.txt, 12.ABCD.txt, 7. ABCD.txt , 8. ABCD.txt, 9. ABCD.txt

我想在我列出的自然人类顺序中阅读它。

这就是我所拥有的

path =os.getcwd()

for root,subdirs,files in os.walk(path):
    sorted(files,key=int)
    for file in files:
        if file.split('.')[-1]=='txt':
            lf=open(os.path.join(root,file), 'r')
            lines = lf.readlines()
            filt_lines = [lines[i].replace('\n', '') for i in range(len(lines)) if lines[i] != '\n']
            alloflines.append(filt_lines) 
            lf.close()  

我也使用了以下

def natural_key(string_):
    return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', string_) if s]
```
To change the key that sorts my files in the order I want, but it keep returning an error.

标签: pythonpython-3.xloopsos.walk

解决方案


您可以简化代码:

  • 首先找到所有文本文件并将它们作为(路径,编号,文件名)的元组存储在列表中
  • 找到所有文件后对元组列表进行排序
  • 处理排序的文件

像这样:

import os
path = os.getcwd()

# stores tuples of (path, number (or 999999 if no number), full filepath)
txt_files = []

for root,subdirs,files in os.walk(path):    
    for file in files:
        if file.endswith(".txt"):
            number, remains = file.split(".",1) # only split into 2, first parsed as number
            if number.isdigit():
                txt_files.append( (root, number, os.join(root,file)) )
            else:
                # txt files not starting with number ordered under 999999
                txt_files.append( (root, 999999, file) )

# tuple-sort: sorts by elements, if same - sorts by next element
# i.e. sorting by path then_by number then_by filename
for path,num,file in sorted(txt_files):
     print( path, num, file)
     # do something with the ordered files

推荐阅读