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

标签 python file

所以我正在研究麻省理工学院免费类(class)中设置的问题。问题是创建一个文字游戏,我已经下载了 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

最佳答案

试试这个:

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

关于Python 无法在我的桌面上找到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21666196/

相关文章:

python - UnicodeEncodeError : 'ascii' codec can't encode character in position 0: ordinal not in range(128)

python - 使用变量从 json 中读取?

python - Django,如何使用过滤器检查参数中是否包含字符串字段

java - java中同时使用InputStream和InputStreamReader

java.io.file 反斜杠保存在 weblogic 的根目录中

python - 零填充 3d Numpy 数组

python - 从 lxml 获取内部 xml

python - 如何按字典顺序对文件路径进行排序? Python

c - 如何在 C 中处理文件 block ?

image - 用于将图像文件大小调整为最大大小并更改大小写的命令行工具