Creating the whole “folder tree” via Python


Please read the code only if you know something about Python 3.x It has been specifically written in Python 3.0

I created this script long back, when I wanted to add all the music file names I had to a database. It would have been tedious to write them all myself. 😦

But as we know, Python is always to the rescue for such kind of works.

import os

a=os.listdir(os.getcwd())
x=input('Write to file(1) or print(2)?')
if x=='1':
 f=open('directory.txt','w',encoding='utf-8')
 for i in a:
 f.write(i+os.linesep)
 f.close()
elif x=='2':
 for i in a:
 print(i)
else:
 print('wrong input... exiting...')

Thus as you can see, the os module can easily get this whole data in seconds (Please see that this work is really easy for Linux users as they can use the kernel to get the data and then then redirect it to a text file. But I haven’t seen such liberties in Windows 😦 )

The above script is a cool one, but does the most simplest work. But what if we require all the files, even inside the folders too.

import os

def folder(a):
 '''extract folders from a list'''
 b=[]
 for i in a:
 if not i.__contains__('.'):
 b.append(i)
 return b

d={}
'''dictionary to store the folder tree'''

def path(pth):
 '''recursively call this func to
 generate the folder tree'''
 d.__setitem__(pth,os.listdir(pth))
 b=folder(d[pth])
 for i in b:
 try:
 path(pth+"\\"+i)
 except WindowsError:
 continue

def show_dict():
 '''print the dictionary'''
 for i in d.keys():
 print(i)
 for j in d[i]:
 print('  '+j)

def print_dict():
 '''write the dictionary to a file'''
 f=open('directory.txt','w',encoding='utf-8')
 for i in d.keys():
 f.write(i+os.linesep)
 for j in d[i]:
 f.write('  '+j+os.linesep)
 f.close()

if __name__=='__main__':
 path(os.getcwd())
 x=input('Write to file(1) or print(2)?')
 if x=='1':
 print_dict()
 elif x=='2':
 show_dict()
 else:
 print('wrong input... exiting...')

The above program is a really good up gradation of the before script as it creates the whole tree of the files in a folder by recursing on the folders inside it.

Explore posts in the same categories: Python

Tags: , , ,

You can comment below, or link to this permanent URL from your own site.

Leave a comment