运行我的代码时出现奇怪的“ FileNotFoundError”

时间:2019-07-13 14:17:07

标签: python python-3.x

我在业余时间写了一个小型的Hangman游戏。该文件夹包含三个文件: main .py,hangman.py和words.txt,其中hangman.py是模块,而words.txt是游戏单词列表。这些文件存储在〜/ projects / hangman(我在Ubuntu上运行)

当我尝试时,它运行完美:

aditya@aditya-VirtualBox:~/projects$ cd hangman
aditya@aditya-VirtualBox:~/projects/hangman$ python3 __main__.py

但是,如果我尝试这样做:

aditya@aditya-VirtualBox:~/projects$ python3 hangman

我最终遇到此错误:

Traceback (most recent call last):
  File "/usr/lib/python3.6/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/usr/lib/python3.6/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "hangman/__main__.py", line 37, in <module>
    while new_game():
  File "hangman/__main__.py", line 21, in new_game
    word = get_word(word_length)
  File "hangman/hangman.py", line 11, in get_word
    with open(filename, 'r') as w:
FileNotFoundError: [Errno 2] No such file or directory: 'words.txt'

在hangman.py中,第11行说:

filename = 'words.txt'

为什么以两种不同的方式运行程序会产生两种不同的结果?

1 个答案:

答案 0 :(得分:1)

尝试提供open()方法的绝对路径。对于python3像这样尝试:

import os as o
path = o.path.abspath(o.path.dirname(__file__))
filename = o.path.join(path, "word.txt")
with open(filename, 'r') as w:
        print(w)