This is for python 2.
I have a chunk of code that is creating an object (dtry) containing three identical lists. Each list is all of the files (excluding folders) with a folder. This works, but I want to extend it to also work for subfolders.
My working code is as follows:
import os
fldr = "C:\Users\jonsnow\OneDrive\Documents\my_python\Testing\Testing"
dtry[:] = [] # clear list
for i in range(3):
dtry.append([tup for tup in os.listdir(fldr)
if os.path.isfile(os.path.join(fldr, tup))])
This successfully creates the three lists containing the names but not full paths of files (and only files, not folders) inside fldr.
I want this to also search within the subfolders of fldr.
Unfortunately I can't figure out how to get it to do so.
I have cobbled together another piece of code that does list all of the files in the subfolders as well (and so kind of works), but it lists the full paths not just the file names. This is as follows:
import os
fldr = "C:\Users\jonsnow\OneDrive\Documents\my_python\Testing\Testing"
dtry[:] = [] # clear list
for i in range(3):
dtry.append([os.path.join(root, name)
for root, dirs, files in os.walk(fldr)
for name in files
if os.path.isfile(os.path.join(root, name))])
I have tried changing the line:
dtry.append([os.path.join(root, name)
to
tup for tup in os.listdir(fldr)
but this is not working for me.
Can anyone tell me what I am missing here?
Again, I am trying to get dtry to be three lists, each list being all of the files within fldr and the files within all of its all of its subfolders.