使用 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.

帕特里克·阿特纳

您可以简化代码:

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

像这样:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章