On 17/08/2019 15:37, Peter Otten wrote:
Paul St George wrote:

Can someone please tell me how to get the absolute path to a file? I
have tried os.path.abspath. In the code below I have a problem in the
final line (15).

#
|import bpy||

Is this blender? If so the "//" prefix starts making sense:

https://docs.blender.org/api/current/bpy.path.html

I'd try bpy.path.abspath() instead of os.pathabspath().


||import os||
||
||texture_list = []||
||
||with open(os.path.splitext(bpy.data.filepath)[0] + ".txt", "w") as
outstream:||
||
||
||for obj in bpy.context.scene.objects:||
||for s in obj.material_slots:||
||if s.material and s.material.use_nodes:||
||for n in s.material.node_tree.nodes:||
||if n.type == 'TEX_IMAGE':||
||texture_list += [n.image]||
||print(obj.name,'uses',n.image.name,'saved at',n.image.filepath, 'which
is at', os.path.abspath(n.image.filepath), file=outstream)||
|#

This gives me:
---Plane uses image01.tif saved at //image01.tif which is at //image01.tif
---Plane uses image02.tif saved at //../images/image02.tif which is at
//images/image02.tif

But I want an absolute path such as:
---Plane uses image01.tif saved at /Users/Lion/Desktop/test8/image01.tif
---Plane uses image02.tif saved at /Users/Lion/Desktop/images/image02.tif

If it is relevant, my files are on a Mac. Hence the escaped forward slash.



Now following Peter's immensely useful nudge towards bpy.path.abspath(), I have learned that Blender uses a special kind of relative path. These paths start with ”//” . The double slashes replace the path to the blend file’s directory.

This means that py.path.abspath() gives a path that is absolute for most of its length then relative towards the end. The good news is that I have found a way to tidy this.

os.path.abspath(bpy.path.abspath(p))

This gives a fully absolute file path. The bpy.path.abspath function takes care of the ’//’ replacing it with the full path to the file, while os.path.abspath takes care of any other unwelcome relative ’../’ that might remain.

Thanks to everyone for their help!
Paul

--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to