Search code examples
pythonuser-interfacetkinterdirectoryuploading

Loading files from directory from user


I'm trying to load a lot of files from a directory. I used to be able to do it by having this

#directory where all data will be stored
dataDir="C:/Users/me/Desktop/Data/"
Files=[] #list of files
for file in os.listdir(dataDir):
    Files.append(scipy.io.loadmat(dataDir+file))

But now, I'm trying to have the user select the folder so I have this:

import tkinter
from tkinter import filedialog
from tkinter import *

root=tkinter.Tk()
filename=filedialog.askdirectory(parent=root,title='Choose a file')
print (filename)


#directory where all data will be stored
dataDir=('%s',filename)
Files=[] #list of files
for file in os.listdir(dataDir):
    Files.append(scipy.io.loadmat(dataDir+file))

and it is giving me this error: "for file in os.listdir(dataDir): TypeError: listdir: path should be string, bytes, os.PathLike or None, not tuple)

I tried making filename into a string by doing str(filename), and it still wouldn't work. Any ideas?


Solution

  • You create tuple in command

    dataDir=('%s',filename) 
    

    and you use it in listdir(dataDir) which expect string

    Use filename directly in listdir

     for file in os.listdir(filename):