python - 什么可能导致此错误: FileNotFoundError: [Errno 2] No such file or directory

标签 python python-3.x error-handling path pathlib

我是编码和Python的新手,所以我对此错误感到非常困惑。
这是练习中的代码,我需要在包含多个文件的目录中找到最常用的单词:

import pathlib

directory = pathlib.Path('/Users/karl/files/Code')

stats ={}

for path in directory.iterdir():
    file = open(str(path))
    text = file.read().lower()

    punctuation  = (";", ".")
    for mark in punctuation:
        text = text.replace(mark, "")


    for word in text.split:
        if word in stats:

            stats[word] = stats[word] + 1
        else:
            stats[word] = 1

most_used_word = None
score_max = 0
for word, score in stats.items():
    if score > score_max:
        score_max = score
        most_used_word = word

print(word,"The most used word is : ", score_max) 
这是我得到的错误:
 for path in directory.iterdir():
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/pathlib.py", line 1113, in iterdir
    for name in self._accessor.listdir(self):
FileNotFoundError: [Errno 2] No such file or directory: '/Users/k/files/Code/exo'
是什么原因导致这种错误?

最佳答案

here's what i guet

for path in directory.iterdir():
 File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/pathlib.py", line 1113, in iterdir
   for name in self._accessor.listdir(self):
FileNotFoundError: [Errno 2] No such file or directory: '/Users/k/files/Code/exo'

what could cause this kind of error ?



导致此错误的最可能原因是没有这样的文件或目录,即文件或目录/Users/k/files/Code/exo不存在。

关于python - 什么可能导致此错误: FileNotFoundError: [Errno 2] No such file or directory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61537231/

相关文章:

python - ModuleNotFoundError : No module named 'rosbag' with pip

python - 使用python在循环时将项目插入列表中

python - 加密 IV - C 和 Python 等效

c++ - 从另一个应用程序在 Cygwin 中运行 bash 命令

python - 聚合和重命名字典中的键

python - 在 numpy 数组的 python 列表中快速查找联合对

Javascript: "throw undefined"安全吗?

error-handling - 如何在关闭时抛出错误?

sql - VBA Excel错误将nvarchar值转换为int

python-3.x - 根据 Python 中另一个数据帧的列对一个数据帧的行(具有重复项的列)进行排序