Reputation:
If I have a structure like such:
root/
-- group1/
---- names/
---- places/
------ foo.zip
Why is that when I call os.path.abspath('foo.zip')
I get the file path of where the Python script is located plus the foo.zip
?
Looks like: H:\Program\Scripts\foo.zip
Needs to be: H:\Progran\Groups\group1\names\places\foo.zip
This is the code I have for a function where the problem is resulting:
def unzip(in_dir):
# in_dir is places passed to unzip()
files = [f for f in os.listdir(os.path.abspath(in_dir)) if f.endswith('.zip')]
for zip in files:
# This prints the 'looks like' path above
print os.path.abspath(zip)
Shouldn't print os.path.abspath(zip)
give me the full path of each file that was found in the os.listdir(os.path.abspath(in_dir))
?
Upvotes: 2
Views: 2175
Reputation: 23139
Why does os.path.abspath() return the path of cwd+file?
Because that's quite literally what abspath
is supposed to do:
os.path.abspath(path)
Return a normalized absolutized version of the pathname path. On most platforms, this is equivalent to calling the function normpath() as follows:
normpath(join(os.getcwd(), path))
.
(Emphasis mine)
Upvotes: 4
Reputation: 781068
os.path.abspath()
has no idea where the name foo.zip
came from -- it doesn't know it came from os.listdir()
of some directory. So it doesn't know that's the correct directory to use as the prefix. A relative pathname is always interpreted relative to the current directory.
If you want to create the desired absolute pathname, use os.path.join
:
print os.path.join(in_dir, zip)
Upvotes: 3