Python无法加载文件

时间:2014-12-30 19:22:20

标签: python file

我正在学习Python,非常感谢您对此问题的建议。

我编写了一个程序,其中包含一些函数来实现一个简单的单词搜索游戏(参见下面的代码)。我得到了一个驱动程序,只有在我的程序正确实现后才能运行。我用示例测试了所有函数,它们似乎工作正常,但是当我运行驱动程序时,我收到此错误消息

>>> 
Traceback (most recent call last):
  File "/Users/<name>/Documents/a3_driver.py", line 88, in <module>
    words = a3.read_words(words_file)
  File "/Users/<name>/Documents/a3.py", line 266, in read_words
    fh = open(words_file)
TypeError: invalid file: None

我认为它与我的第二个最后一个名为 read_words 的函数有关,但我似乎无法解决问题。任何反馈都会非常感激,我在下面已经包含了这个函数的代码(我还包括了最后一个函数,也称为read_board,因为它非常相似,并且还读取了一个txt文件,以防万一我和#39;我两次犯同样的错误)。提前谢谢

可以从本页底部下载游戏的驱动程序: http://spark-public.s3.amazonaws.com/programming1/a3/a3.html

read_words 函数创建一个由文件中的单词组成的单词列表。

def read_words(words_file):
    """ (file open for reading) -> list of str

    Return a list of all words (with newlines removed) from open file
    words_file.

    # A simple .txt file used in this function simply contains the 4 words below, each printed on a new line 
    CRUNCHY
    COWS
    EAT
    GRASS

    >>> read_words('wordlist1.txt')
    ['CRUNCHY', 'COWS', 'EAT', 'GRASS']

    Precondition: Each line of the file contains a word in uppercase characters
    from the standard English alphabet.
    """

    fh = open(words_file)

    lst = []

    for line in fh:
        line = line.strip()
        for i in line.split():
            lst.append(i)

    return lst
    #print (lst)

    fh.close()

read_board 函数创建一个由文件中的字母行组成的板。

def read_board(board_file):
    """ (txt file) -> list of list of str

    # A simple txt file used in this example contains the following...
    EFJAJCOWSS
    SDGKSRFDFF
    ASRJDUSKLK
    HEANDNDJWA
    ANSDNCNEOP
    PMSNFHHEJE
    JEPQLYNXDL

    >>> read_board('board1.txt')
    [['EFJAJCOWSS'], ['SDGKSRFDFF'], ['ASRJDUSKLK'], ['HEANDNDJWA'], ['ANSDNCNEOP'], ['PMSNFHHEJE'], ['JEPQLYNXDL']]


    Return a board read from open file board_file. The board file will contain
    one row of the board per line. Newlines are not included in the board.
    """

    data = []

    fh = open(board_file)

    for line in fh:
        items = line.rstrip('\r\n').split('\t')   # strip new-line characters and split     on column delimiter
        data.append(items)

    return data

    fh.close()

1 个答案:

答案 0 :(得分:1)

查看您链接到的驱动程序,我看到这些行调用了read_words函数:

words_file = askopenfile(mode='r', title='Select word list file')
words = a3.read_words(words_file)
words_file.close()

正如其他人所指出的那样,askopenfile返回的是None。我建议您尝试使用此功能并确定原因。我怀疑你输入的文件名不在你认为的位置,这就是你没有收到文件的原因。

此外,一些研究表明,askopenfile返回一个文件句柄,而不是文件名 - 你的代码假定你得到一个文件名(因此你打开它),这也是不正确的。