absolute path to a file

Paul St George email at paulstgeorge.com
Fri Aug 16 12:26:00 EDT 2019


Thank you Manfred and Cameron!
I think the problem may lie within syntax rather than vocabulary. The 
code works in one place but not where I use it in my script*. Cameron’s 
suggestion works when I try

| print('test1:', os.path.realpath(bpy.data.filepath))|

This returns:
|/Users/Lion/Desktop/test8/tifftest8.blend|


BUT does not work with
| print('test2:',os.path.realpath(n.image.filepath))|

This returns only
|/image01.tif|


Here is my full script:
# starts

|import bpy||
||import os||
||from pathlib import Path ||
||
||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.realpath(n.image.filepath), file=outstream)||
||||
|# ends

Notes:
Chris, I only mention the extra leading slash on my Mac in case anyone 
wonders why it is there. Python puts it there to escape the following slash.
Perhaps I should also mention (in case it is relevant) that I am calling 
my script ‘texturescript.py’ from the Python console of Blender. I use:

|filename = "/Users/Lion/Desktop/test8/texturescript.py"||
||exec(compile(open(filename).read(), filename, 'exec'))|


* My original |os.path.abspath| also works (and doesn’t work) in these 
circumstances. As does Manfred’s: |Path('./myfile').resolve()|.

On 16/08/2019 05:44, Manfred Lotz wrote:
> On Fri, 16 Aug 2019 09:00:38 +1000
> Cameron Simpson <cs at cskk.id.au> wrote:
>
>> On 15Aug2019 22:52, Manfred Lotz <ml_news at posteo.de> wrote:
>>> I did this:
>> >from pathlib import Path
>>> abs_myfile = Path('./myfile').resolve()
>>> which worked fine for me.
>> There is also os.path.realpath(filename) for this purpose. In modern
>> Python that also accepts a Pathlike object.
> Thanks for this.
>
> I changed my code to use your suggestion which seems to
> be better for the situation where I used resolve() before.
>
-- 
Paul St George
http://www.paulstgeorge.com
http://www.devices-of-wonder.com

+44(0)7595 37 1302




More information about the Python-list mailing list