the input would be something like this " /usr/bin/blah /sbin/blah /usr/share/man/man1/blah " for line in lines: if os.path.islink(line.rstrip()): main.write("ln -sf "+os.path.realpath(line.rstrip())+" "+line.rstrip()+"\n") remove.write("rm "+line.rstrip()+"\n") else: localdest=line.rstrip().split("/")[len(line.rstrip().split("/"))-1]+str(counter) folders = line.rstrip().split("/") folder = "" for fol in folders[:-1)]: folder = folder+fol+"/" dirs.append(folder) #main.write("if [ ! -d "+folder+" ] ; then mkdir -p "+folder+" ; fi\n") shutil.copyfile(line.strip(), localdest) shutil.copymode(line.strip(), localdest) main.write("cp -p "+localdest+" "+line.rstrip()+"\n") remove.write("rm "+line.rstrip()+"\n") counter+=1 print(dirs) and the way i want dirs to look is ['/usr/bin','/sbin','/usr/share/man/man1'] but currently, with the way i am doing it it is coming out like ['/', '/sbin/'] ['/', '/sbin/', '/sbin/'] ['/', '/sbin/', '/sbin/', '/sbin/'] ['/', '/sbin/', '/sbin/', '/sbin/', '/sbin/'] ['/', '/sbin/', '/sbin/', '/sbin/', '/sbin/', '/sbin/'] ['/', '/sbin/', '/sbin/', '/sbin/', '/sbin/', '/sbin/', '/sbin/']