简体   繁体   English

为什么我在 python 中收到“FileNotFoundError”?

[英]Why do I get a ''FileNotFoundError'' in python?

I have a list of the xlsx files in my directory and subdirectories and I want to loop through this list with certain conditions.我的目录和子目录中有一个 xlsx 文件列表,我想在某些条件下循环遍历此列表。 Now it seems that the code works for the main directory, but it has troubles opening the files within the subdirectories.. I used the os.walk method but I still get the error ''[Errno 2] No such file or directory: 'file name'''.现在看来该代码适用于主目录,但在打开子目录中的文件时遇到问题。我使用了 os.walk 方法,但仍然出现错误“[Errno 2] 没有这样的文件或目录:”文档名称'''。 The error occurs at the last piece of the code, the part that starts with 'for f in files: if f.endswith('.xlsx'): and so on..错误发生在代码的最后一段,即以 'for f in files: if f.endswith('.xlsx'): 开头的部分,依此类推。

How to fix this problem?如何解决这个问题?

path = os.getcwd()
files = os.listdir(path)

directories = ['2018', '2017', '2016', '2015']

for directory in directories:
   directory_path = os.path.join(path, directory)
   files_in_directory = os.listdir(directory_path)
   for file in files_in_directory:
       files.append(file)


 filtered_files_list = []

 for f in files:
    if f.endswith('.xlsx'):      
       wb = openpyxl.load_workbook(f)
       if "2014" in wb.sheetnames:
           filtered_files_list.append(f)

 for root, dirs, files in os.walk(path):
   if root.endswith("2018") or root.endswith("2017") or root.endswith("2016") or root.endswith("2015"):
        for f in files:
           if f.endswith('.xlsx'):               
               wb = openpyxl.load_workbook(os.path.join(root, f))
               if "2014" in wb.sheetnames:
                   filtered_files_list.append(f)

print(filtered_files_list)

Your listdir + walk combination sounds like it could be simplified with a pathlib.Path.glob , which will also give you full paths without the need to join .您的listdir + walk组合听起来可以使用pathlib.Path.glob进行简化,它还可以为您提供完整路径而无需join

from pathlib import Path
from openpyxl import load_workbook

filtered_files_list = []

filter_directories = {"2015", "2016", "2017", "2018"}  # set for fast search

p = Path(".")  # equivalent to getcwd
for xlsx in p.glob("./**/*.xlsx"):  # recursive search for all XLSX under CWD
    if str(xlsx.parents[-2]) not in filter_directories:  # skip if not in filter_directories
        continue
    wb = openpyxl.load_workbook(xlsx)
    if "2014" in wb.sheetnames:
        filtered_files_list.append(xlsx)

In the following hierarchy it finds:它在以下层次结构中找到:

.
├── 2015
│   ├── has-2014-sheet.xlsx
│   └── no-2014-sheet.xlsx
├── 2016
│   └── sub
│       ├── has-2014-sheet.xlsx
│       └── no-2014-sheet.xlsx
├── 2020
│   ├── has-2014-sheet.xlsx
│   └── no-2014-sheet.xlsx
└── other
    ├── has-2014-sheet.xlsx
    └── no-2014-sheet.xlsx
[PosixPath('2015/has-2014-sheet.xlsx'),
 PosixPath('2016/sub/has-2014-sheet.xlsx')]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么 FileNotFoundError: [Errno 2] 如果我在 Python 中有它,则没有这样的文件或目录? - Why FileNotFoundError: [Errno 2] No such file or directory if I do have it in Python? 为什么在用Django执行文件上传时出现“ FileNotFoundError”? - why do I get “FileNotFoundError” when doing fileupload with Django? 为什么在使用子进程时会收到 FileNotFoundError? - Why do I get a FileNotFoundError when using subprocess? 为什么在使用 subprocess.Popen 时会出现 FileNotFoundError? - Why do I get FileNotFoundError when using subprocess.Popen? 如何从 Python 3 导入 FileNotFoundError? - How do I import FileNotFoundError from Python 3? 当我使用“除了 FileNotFoundError”function 时,为什么 python 需要一个语句? “FileNotFoundError”不是已经声明了吗? - Why does python expects a statement when I use "except FileNotFoundError" function? Isn't the "FileNotFoundError" already a statement? 为什么我收到 FileNotFoundError? - Why am I getting FileNotFoundError? 为什么我会收到 FileNotFoundError? - Why am I getting a FileNotFoundError? 为什么我会在 python 中遇到这个网页抓取问题? - Why do I get this webscraping issue in python? 为什么在Python的线程处理中出现TypeError - Why do I get TypeError in Threading in Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM