Python - FileNotFoundError:[Errno 2]没有这样的文件或目录

时间:2017-10-23 03:26:14

标签: python

titles = [line.rstrip() for line in open('./nlp_class/all_book_titles.txt')]

# copy tokenizer from sentiment example
stopwords = set(w.rstrip() for w in open('./nlp_class/stopwords.txt'))

我试图运行python文件' books.py'但它给出了这个错误:

Traceback (most recent call last):
  File "books.py", line 14, in <module>
    titles = [line.rstrip() for line in open('./nlp_class/all_book_titles.txt')]
FileNotFoundError: [Errno 2] No such file or directory: './nlp_class/all_book_titles.txt'

完整目录为: C:\ Python36 \ python_bible \ nlp_class
&#39; books.py&#39;文件位置: C:\ Python36 \ python_bible \ books.py
完整代码位于:https://jsfiddle.net/4rd2knbu/

1 个答案:

答案 0 :(得分:0)

我怀疑问题是您在Windows系统上使用UNIX路径分隔符/而不是使用Windows路径分隔符\。您可以使用os.path.join编写与操作系统无关的代码(它将自动使用正确的分隔符):

import os

titles_file = os.path.join("nlp_class", "all_book_titles.txt")
titles = [line.rstrip() for line in open(titles_file)]

# copy tokenizer from sentiment example
stopwords_file = os.path.join("nlp_class", "stopwords.txt")
stopwords = set(w.rstrip() for w in open(stopwords_file))