简体   繁体   中英

python FileNotFoundError

I was writing a program that accesses a .txt file at the start of the program with the open() function. It ran without any errors on the IDE and I was also able to read the text file when running from the IDE without any issues. Although when I ran from the Python Launcher it threw a "FileNotFoundError" Here's my code:

directions_object = open('warcards_directions.txt','r')

Further to Dan D's comment.. try putting this on the line in front of your open() call:

 from os.path import abspath
 print(abspath('warcards_directions.txt'))

You'll see that python looks in different places depending on where you run it from .. because it looks for files relative to the current working directory, which changes depending on how you run python.

This is a common problem for new comers. See here How to import files in python using sys.path.append? for some solutions (note the underlying problem in that post is the same as this one.. the fact that they're trying to import a file, and here we're trying to open one is not too important).

Also I'll add that I often reference things relative to the script itself... like this:

from os.path import abspath, join, dirname

script_dir = dirname(__file__)
txt_path = abspath(join(script_dir, "..", "path", "to", "warcards_directions.txt"))

This works if your txt file and your python script stay in the same place relative to each other (but might be installed in different places).

Eg above assumes your script lives in C:\\Foo\\scripts\\script.py and your text file lives in C:\\Foo\\path\\to\\warcards_directions.txt. The method above will work fine where ever you run the script from and it'll work if you move or rename the C:\\Foo dir (eg to C:\\Program Files\\Bar). But it'll break if you decide to move scripts.py down a directory into C:\\Foo (at which point you change the way txt_path is initialized to fix).

When you said "python launcher", do you mean the command line?

python myScript.py

If you, you will need to cd into the directory where the file is at before you can execute the script. Otherwise, provide the full path to the txt file in your script.

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