[Tutor] code works in windows command but not ubuntu terminal
Steven D'Aprano
steve at pearwood.info
Sat Jan 25 02:38:18 CET 2014
On Fri, Jan 24, 2014 at 04:31:49PM -0500, Keith Winston wrote:
> On Fri, Jan 24, 2014 at 4:50 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> > Python does not use a search path for the open() function, only for
> > imports. With open(), it uses a simple rule:
> >
> > - absolute paths will look only in that exact location;
> >
> > - relative paths are always relative to the current working directory.
> >
> > Do you know the difference between absolute and relative paths?
>
> Ah! I was just running into this... I did not know that. So there's no
> way to get it to search a path (other than coding some string
> concatenation of path names or something, of course) to open a file?
Of course there is -- you just have to program it yourself!
First, decide whether the filename is absolute or relative. Absolute
filenames should not search the path. Then, if it is relative, loop over
your "open path list" like this:
for prefix in open_path_list:
location = os.path.join(prefix, filename)
try:
f = open(location)
except IOError:
pass
else:
break
However, there's more to it than this. For starters, you need to decide
on the exact behaviour. Clearly, "file not found" errors should move on
to try the next prefix in the path list. But what about permission
denied errors?
--
Steven
More information about the Tutor
mailing list