text files - python FileNotFoundError -


i writing program accesses .txt file @ start of program open() function. ran without errors on ide , able read text file when running ide without issues. although when ran python launcher threw "filenotfounderror" here's code:

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

further dan d's comment.. try putting on line in front of open() call:

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

you'll see python looks in different places depending on run .. because looks files relative current working directory, changes depending on how run python.

this common problem new comers. see here how import files in python using sys.path.append? solutions (note underlying problem in post same one.. fact they're trying import file, , here we're trying open 1 not important).

also i'll add reference things relative script itself... 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 txt file , python script stay in same place relative each other (but might installed in different places).

e.g. above assumes script lives in c:\foo\scripts\script.py , text file lives in c:\foo\path\to\warcards_directions.txt. method above work fine ever run script , it'll work if move or rename c:\foo dir (e.g. c:\program files\bar). it'll break if decide move scripts.py down directory c:\foo (at point change way txt_path initialized fix).


Comments

Popular posts from this blog

c# - Binding a comma separated list to a List<int> in asp.net web api -

Delphi 7 and decode UTF-8 base64 -

html - Is there any way to exclude a single element from the style? (Bootstrap) -