1

how to list names of all files from selected directory and sub directories with in directory using tkinter. Here is my code .

def openDirectory(self):
        self.dirname = tkFileDialog.askdirectory(parent=self.root, 
        initialdir='/home/', title='Select your database' )
        self.files=os.listdir(self.dirname)
        print self.files

it just list files in directory. if directory contains sub directories, it gave error message .I want to list all files of directory and sub directories files name.

Muhammad
  • 33
  • 10

1 Answers1

1

Two things:

  1. os.listdir should provide you with the names of all the items in the specified path. This includes both files and directories: https://docs.python.org/2/library/os.html#os.listdir. If you want to get the full path from os.listdir, you might try

self.files = [os.path.join(self.dirname, item) for item in os.listdir(self.dirname)]

  1. A different option is using the module glob. If you hand glob.glob a full path, it should give you a list of all items as well. E.g.:

    from glob import glob ... self.files = glob(os.path.join(self.dirname, '*'))

AetherUnbound
  • 1,714
  • 11
  • 10
  • please edit my code .. my requirement is just print all files name that are present in directory and also in sub directories @AetherUnbound – Muhammad Jul 14 '17 at 06:27
  • Did you want the full path or just the name? – AetherUnbound Jul 14 '17 at 19:04
  • def openDirectory(self): self.dirname = tkFileDialog.askdirectory(parent=self.root, initialdir='/home/', title='Select your database' ) path=self.dirname for root, dirs, self.files in os.walk(path): for file in self.files: if file.endswith('.txt') | file.endswith('.pdf') | file.endswith('.pptx') | file.endswith('.docx') | file.endswith('.csv') | file.endswith('.xlsx'): #files=os.listdir(self.dirname) print (os.path.join(root, file)) – Muhammad Jul 16 '17 at 04:38
  • i used the above code to access all files name and succeed .. now i want to store all these files in a an array .. how can i do that ? @AetherUnbound – Muhammad Jul 16 '17 at 04:40
  • Do you want the full path of the file or just the filename? – AetherUnbound Jul 17 '17 at 14:47
  • I am making a similarity checker app .. similarity checker uses local drive as a database (e.g. drive D) and it have to access all the files present in different folders of drive so that it can check similarity between input file and database files one by one .. everything is working .. my problem is that i am not able to access all files and save them on one place to check plagiarism easily .. @AetherUnbound – Muhammad Jul 18 '17 at 17:03
  • You didn't quite answer my question. It also sounds like this is a different problem than the one you posted about; it might be a good idea to make a new post. – AetherUnbound Jul 18 '17 at 18:27