What does local relative filename means in Python? -
i found, proceess files given filename need do
import os dir = os.path.dirname(__file__) filename = os.path.join(dir, '/relative/path/to/file/you/want')
or
import os dir = os.getcwd() filename = os.path.join(dir, '/relative/path/to/file/you/want')
but if do
filename = 'myfile.txt'
then file?
short answer: in current working directory.
long answer:
from https://docs.python.org/2/library/stdtypes.html#bltin-file-objects
file objects implemented using c’s stdio package
from https://docs.python.org/2/library/functions.html#open
the first 2 arguments same stdio‘s fopen(): name file name opened
so, answered looking @ documentation stdio
:
from http://www.cplusplus.com/reference/cstdio/fopen/
filename
c string containing name of file opened.
its value shall follow file name specifications of running environment , can include path (if supported system).
"specifications of running environment" means interpret if typed path running file from, aka, cwd.
for example, if have script located in ~/desktop/temp.py
reads:
f = open("log.txt", 'r') print "success opening" f.close()
and have file located @ ~/desktop/log.txt
, following output:
~/desktop $ python temp.py success opening
but if cd ..
, try again:
~ $ python ~/desktop/temp.py traceback (most recent call last): file "/home/whrrgarbl/desktop/temp.py", line 1, in <module> f = open("log.txt", 'r') ioerror: [errno 2] no such file or directory: 'log.txt'
just verify:
~ $ touch log.txt ~ $ python ~/desktop/temp.py success opening
so can see trying open relative directory ran script from, not directory in script located.
Comments
Post a Comment