GIMP Chat
http://gimpchat.com/

reading a folder of text files (problem solved)
http://gimpchat.com/viewtopic.php?f=8&t=18155
Page 1 of 1

Author:  dinasset [ Sat Mar 28, 2020 10:51 am ]
Post subject:  reading a folder of text files (problem solved)

GIMP Version: 2.10.18 samj
Operating System: Windows
GIMP Experience: Moderate



I have a bit of experience in writing plug-ins in python for image manipulation, but none in browsing text files from the plug-in.
I prepared a folder on my desktop called MyPresets.
I wrote a test filter with the following instructions (copied somewhere on the net)
def LoadPresets (inFolder) :
   
    home = expanduser("~")
    i_dir = home+inFolder
    gimp.message (str(i_dir))
   
    # Read every file in directory
    for filename in os.listdir(i_dir):
        gimp.message (str(filename))

        #with open(filename, "r") as f:
        with open(filename,"r") as f:    ### DOES NOT FIND IT ?????
            # Read each line of the file
            for line in f.readlines():
                gimp.message (line.split())   
   
    return

The inFolder field contains "\Desktop\MyPresets"
I got the messages I wrote for tracing but then I got the error as shown:
Attachment:
Cattura.PNG
Cattura.PNG [ 36.43 KiB | Viewed 2237 times ]


Why the file is not found?

Sorry for my ignorance in that type of instructions.

Any help?

Author:  dinasset [ Sat Mar 28, 2020 3:15 pm ]
Post subject:  Re: reading a folder of text files (solved)

self solution?

it seems that I have to enter
with open(i_dir+filename,"r") as f:
i.e. repeating the full path

quite surprising for an ignorant like me, but if this is the solution, OK...

Author:  ofnuts [ Sat Mar 28, 2020 5:45 pm ]
Post subject:  Re: reading a folder of text files (solved)

dinasset wrote:
self solution?

it seems that I have to enter
with open(i_dir+filename,"r") as f:
i.e. repeating the full path

quite surprising for an ignorant like me, but if this is the solution, OK...


os.listdir() gives you the names of the files in the listed directory, so yes, you have to add the directory to that to access the file. This is best done using os.path.join(dir,file) (because the right separator for the OS will be added automatically).

Alternatively you can use glob.glob() that allows you to specify a file pattern:
import glob
files=glob.glob(os.path.join(dir ,'*.txt'))

Author:  dinasset [ Sat Mar 28, 2020 11:47 pm ]
Post subject:  Re: reading a folder of text files (problem solved)

Thanks!
In my ignorance on the subject I thought that -once accessed thru the listdir- the "path" was "remembered" by the python filter.
Ok, I can proceed now.

Page 1 of 1 All times are UTC - 5 hours [ DST ]
Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group
http://www.phpbb.com/