Python无法在我的桌面上找到文件

时间:2014-02-09 22:50:42

标签: python file

所以我正在解决麻省理工学院免费课程中的问题。问题是创建一个文字游戏,我已经下载了一个84,000个单词的列表,它将作为一个字典。该文件位于我的桌面,我已尝试在PyCharm中输入特定位置但由于某种原因无法找到该文件。我曾尝试将文件存储在不同的地方和表单中,但无法找到它。这是错误追溯:

File "/Users/ksorenson/PycharmProjects/Word Game/ps5cheat_sheet.py", line 241, in <module>
    word_list = load_words()

File "/Users/ksorenson/PycharmProjects/Word Game/ps5cheat_sheet.py", line 33, in load_words
    inFile = open(WORDLIST_FILENAME, 'r', 0)

FileNotFoundError: [Errno 2] No such file or directory: 'words.txt'

以下是一些代码:

# Problem Set 5: 6.00 Word Game
# Name:
# Collaborators:
# Time:
#

import random
import string

VOWELS = 'aeiou'
CONSONANTS = 'bcdfghjklmnpqrstvwxyz'
HAND_SIZE = 7

SCRABBLE_LETTER_VALUES = {
    'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10
}

# -----------------------------------
# Helper code
# (you don't need to understand this helper code)

WORDLIST_FILENAME = "words.txt"  *************HERE IS THE FILE THAT I CANNOT LOCATE*********

def load_words():
    """
    Returns a list of valid words. Words are strings of lowercase letters.

    Depending on the size of the word list, this function may
    take a while to finish.
    """
    print("Loading word list from file...")
    # inFile: file
    inFile = open(WORDLIST_FILENAME, 'r', 0)
    # wordlist: list of strings
    wordlist = []
    for line in inFile:
        wordlist.append(line.strip().lower())
    print("  ", len(wordlist), "words loaded.")
    return wordlist

2 个答案:

答案 0 :(得分:1)

请改为尝试:

import os
WORDLIST_FILENAME = os.path.expanduser("~/Desktop/words.txt")

答案 1 :(得分:0)

我同意Cfreak。它正在尝试打开words.txt,它将其解释为相对路径,并且由于路径中没有目录规范,因此脚本需要位于当前工作目录中(通常与脚本相同) 。以wim建议的方式修改脚本,或将words.txt移动到与脚本相同的目录中。