![](/img/trans.png)
[英]Why FileNotFoundError: [Errno 2] No such file or directory if I do have it in Python?
[英]Why do I get a ''FileNotFoundError'' in python?
我的目錄和子目錄中有一個 xlsx 文件列表,我想在某些條件下循環遍歷此列表。 現在看來該代碼適用於主目錄,但在打開子目錄中的文件時遇到問題。我使用了 os.walk 方法,但仍然出現錯誤“[Errno 2] 沒有這樣的文件或目錄:”文檔名稱'''。 錯誤發生在代碼的最后一段,即以 'for f in files: if f.endswith('.xlsx'): 開頭的部分,依此類推。
如何解決這個問題?
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)
您的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)
它在以下層次結構中找到:
.
├── 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.