python - 使用 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
推荐阅读
- ruby - SocketError:sockaddr 解析为多个节点名
- node.js - Blazor Server 与 socket.io 的合作
- windows - 您好,我尝试在 dev-c++ 中运行我的 c 代码并得到以下信息:[错误] 'for' 循环初始声明仅在 C99 或 C11 模式下允许
- web - 如何在 Web 应用程序中集成签名板
- laravel - 如何从多个控制器获取数据到 Laravel Blade 视图中?
- javascript - Glide.js 滑块未在最后一张幻灯片上暂停
- prometheus-alertmanager - AlertManager 队列正在丢弃消息
- android - 导航栏上的黑色条纹 (AOSP)
- html - 如何使 div 适当地扩大和缩小?
- fpga - ISE 设计套件 14.7 中的“目标不支持逻辑根块和符号”错误