python 递归获取文件

2023-12-12

我有一个文件夹结构:

我正在使用 os.walk(path) 从“test”文件夹中获取所有文件。我想要除文件夹“B”及其内部文件之外的所有文件。

测试(根文件夹)

  • t1.txt
  • t2.txt
  1. A
  • f.txt
  1. B
  • f1.txt
  1. C
  • f4.txt
list1 = ['A', 'C']
result = [os.path.join(dp, f) for dp, dn, filenames in os.walk(path) for f in filenames if os.path.splitext(f)[1] == '.txt']
  for items in result:
     for fname in list1:
       if fname in items.lower():
         result.remove(items)

print(result)

我试过了,但只需要A和C。而不是主文件夹中的文件?你能帮我吗?我哪里错了?

谢谢


可能的解决方案是使用 glob 库:

import glob

dir_to_exclude = ['B', 'C']

files = glob.glob('**/*.txt', recursive=True)
files_paths = [_ for _ in files if _.split("\\")[0] not in dir_to_exclude]
files_names = [_.split("\\")[-1] for _ in files if _.split("\\")[0] not in dir_to_exclude]

print(f'List of file names with path: {files_paths}')
print(f'List of file names: {files_names}')
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

python 递归获取文件 的相关文章

随机推荐