Switch to full style
Ask all general Gimp related questions here
Post a reply

reading a folder of text files (problem solved)

Sat Mar 28, 2020 10:51 am

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)
Code:
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:
Cattura.PNG
Cattura.PNG (36.43 KiB) Viewed 2239 times


Why the file is not found?

Sorry for my ignorance in that type of instructions.

Any help?

Re: reading a folder of text files (solved)

Sat Mar 28, 2020 3:15 pm

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...

Re: reading a folder of text files (solved)

Sat Mar 28, 2020 5:45 pm

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:
Code:
import glob
files=glob.glob(os.path.join(dir ,'*.txt'))

Re: reading a folder of text files (problem solved)

Sat Mar 28, 2020 11:47 pm

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.
Post a reply