如何修复FileNotFoundError Errno 2没有这样的文件或目录

时间:2018-06-02 10:52:43

标签: python python-3.6

我已经完成了一些提供的解决方案,但它并没有帮助我。请有人告诉我我失踪了什么

from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
import os.path

bot = ChatBot('Cuibot') 
bot.set_trainer(ListTrainer)

for files in os.listdir('C:\\Users\\AMINDE64\\Chat\\chatterbot-corpus- 
1.1.2\\chatterbot_corpus\\data\\english'): 
data = open('C:\\Users\\AMINDE64\\chat\\chatterbot-corpus- 
1.1.2\\chatterbot_corpus\\data\\english' + files, "r").readlines()
bot.train(data)

while True:
    message = input('You:')
    if message.strip() != 'Bye':
    reply = bot.get_response(message)
               print('ChatBot :', reply) 
    if message.strip() == 'Bye':
    print('ChatBot : Bye')
   break

1 个答案:

答案 0 :(得分:0)

首先,使代码更具可读性,例如:

dirname = 'C:\\Users\\AMINDE64\\Chat\\chatterbot-corpus- 
    1.1.2\\chatterbot_corpus\\data\\english'

for filename in os.listdir(dirname): 
    data = open(dirname + filename, "r").readlines()
    bot.train(data)

现在它可读,但仍然无效。

然后,使用os.path.join加入路径,使用with确保文件正确关闭:

for filename in os.listdir(dirname): 
    with open(os.path.join(dirname, filename), "rt") as f:
        data = f.readlines()
    bot.train(data)