简体   繁体   中英

Trying to read a text file in Python, getting IOError(2, 'No such file or directory')

so I'm trying out this ScrabbleCheat challenge from https://openhatch.org/wiki/Scrabble_challenge

I followed the code found here, placed it into a project in PyCharm, but getting stuck on the f = open(input_file, 'r') line, says it can't find my sowpods.txt file :(

在此处输入图片说明

Now when I try the code from the terminal it will actually run! :( However I'm trying to build an interface for my project so would like to get out of the terminal as quickly as possible.

在此处输入图片说明

The text file is in the right place

在此处输入图片说明

Problem code, any thoughts?

from __future__ import print_function
from flask import Flask
import string
import sys
import sqlite3 as sqlite

app = Flask(__name__)


def test_for_db():
    # test for existance of  sowpods database
    pass


def test_for_sowpods():
    # test for existence of sowpods  text file
    pass


def word_score(input_word):
    # score the word
    # need to account for the blanks
    scores = {"a": 1, "c": 3, "b": 3, "e": 1, "d": 2, "g": 2,
            "f": 4, "i": 1, "h": 4, "k": 5, "j": 8, "m": 3,
            "l": 1, "o": 1, "n": 1, "q": 10, "p": 3, "s": 1,
            "r": 1, "u": 1, "t": 1, "w": 4, "v": 4, "y": 4,
            "x": 8, "z": 10}

    word_score = 0

    for letter in input_word:
        word_score = word_score + scores[letter]

    return word_score


def word_list(input_file):
    # create a list of tuples which containing the word, it's length, score and sorted value

    sp_list = []
    f = open(input_file, 'r')

    for line in f:
        sp_word = line.strip().lower()
        sp_list.append((sp_word, len(sp_word), ''.join(sorted(sp_word)), word_score(sp_word)))

    f.close()

    return sp_list


def load_db(data_list):

    # create database/connection string/table
    conn = sqlite.connect("sowpods.db")

    cursor = conn.cursor()
    # create a table
    tb_create = """CREATE TABLE spwords
            (sp_word text, word_len int, word_alpha text, word_score int)
            """
    conn.execute(tb_create)
    conn.commit()

    # Fill the table
    conn.executemany("insert into spwords(sp_word, word_len, word_alpha, word_score) values (?,?,?,?)",  data_list)
    conn.commit()

    # Print the table contents
    for row in conn.execute("select sp_word, word_len, word_alpha, word_score from spwords"):
        print (row)

    if conn:
        conn.close()


def print_help():
    """ Help Docstring"""
    pass


def test():
    """ Testing Docstring"""
    pass

if __name__=='__main__':
    # test()
    sp_file = "sowpods.txt"
    load_db(word_list(sp_file))
    app.run(debug=True)

You're using a relative path for your input file, which means your script will only work if you are running your script with the same working directory as your "sowpods.txt" file. Switch to using a full path, so your script will work no matter what the working directory of the script is.

Here's how: In your if __name__=='__main__': block at the end, instead of using

sp_file = "sowpods.txt"

use the full path:

sp_file = "/Users/leongaban/scrabblechallenge/path/to/your/file/sowpods.txt"

(of course substituting whatever the full path to your file is)

When you create a GUI for your program, you could have the user choose the file, and call word_list with the resulting file path as the argument.

The path "sowpods.txt" means "The file named sowpods.txt in whatever directory happens to be the current working directory at the moment."

If you want "The file named sowpods.txt in the same directory as the script", you have to say so, like this:

import os
scriptdir = os.path.dirname(os.path.abspath(__file__))

sp_file = os.path.join(scriptdir, "sowpods.txt")

Note that in a real-life program or module that you plan to distribute, you'll probably want something a little more complicated, where your setup.py file configures an appropriate (for each machine) location for the file. (You can't rely on scripts and their data files being installed alongside each other on most platforms.)


If you run the script from the command line, the current working directory is obvious, because you can see it in the shell. For example, on Windows:

C:\> C:\Python27\python.exe C:\Users\me\MyScripts\myscript.py

… the current working directory here is C:\\ . To make it work, you'd have to do this:

C:\> cd C:\Users\me\MyScripts\
C:\Users\me\MyScripts\> C:\Python27\python.exe .\myscript.py

If you run the script by double-clicking it, where it runs depends on your OS and version—it may be your system's root directory, or your home directory, or something else entirely. There's probably no way to make it work.

And if you run the script from inside an IDE, it's probably configurable by the IDE. In PyCharm, it's part of your project's "Run/Debug Configuration".

But really, you don't want a script that can be used only when you do things exactly in a certain way; you want a script that works however you run it.

I suggest trying the following

import os
#get the directory your script is located in which also has the file you're trying to read
path = os.path.abspath(os.path.dirname(__file__))
fullpath = os.path.join(path,input_file)
f = open(fullpath,"rt") # instead of your current open

Brionius' answer works, but isn't portable for when you want to move your script somewhere else.

What you're experiencing is actually a problem with your PyCharm configuration. You'll want to change your PyCharm working directory, as documented here . Namely, you'll want to change your working directory to where "sowpods.txt" is currently located.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM