iteration - Unexpected behaviour while iterating directories in python -
i'm making inventory of files in big library. idea write paths in column, parent directory of file in other colum, , files in other column.
i need write parent directory in corresponding cell each file , means writing folder's name many times there files inside it.
this have far:
import os import openpyxl def crearlista (*arg, **kw): inventario = openpyxl.workbook(encoding = "utf-8") sheet = inventario.active = 1 e = "" dirpath, subdirs, files in os.walk("//media//rayeus/datos/mis documentos/nueva carpeta/", topdown=false): name in subdirs: e = os.path.join (name) name in files: sheet.cell(row=i, column=3).value = name sheet.cell(row=i, column=1).value = dirpath sheet.cell(row=i, column=2).value = e = + 1
this works perfectly: iterates through every file in folder , writes name , dirpath in desired locations. problem starts iterating through files in first folder without filling e variable. first 3 rows in second column 3 blank cells, , after fills following cells name of folders in order (each 1 of names repeated many times number of files in next folder instead of number of files on correspondent folder)
essentially problem iterates through files in first folder before filling e variable correspondent folder name.
in other words, writing of files name , dirpath going 1 step further writing of parent directory messes second column completely.
example of output file:
nueva carpeta/-assorted-/the.galactic.black.hole.lectures.on (3587) " " cover.jpg nueva carpeta/-assorted-/the.galactic.black.hole.lectures.on (3587) " " metadata.opf nueva carpeta/-assorted-/the.galactic.black.hole.lectures.on (3587) " " the.galactic.black.hole.lecture - -assorted-.pdf nueva carpeta/100 recetas de cocina espanola/http___www.recetas.net_admin_libros (5831) the.galactic.black.hole.lectures.on (3587) cover.jpg nueva carpeta/100 recetas de cocina espanola/http___www.recetas.net_admin_libros (5831) the.galactic.black.hole.lectures.on (3587) http___www.recetas.net_admin_li - 100 recetas de cocina espanola.pdf nueva carpeta/100 recetas de cocina espanola/http___www.recetas.net_admin_libros (5831) the.galactic.black.hole.lectures.on (3587) metadata.opf
if file 'a/b/c/x.txt', dirpath
'a/b/c' , 'x.txt' should in files
. basename(dirpath)
return 'c'.
if dirpath
ends slash 'a/b/c/', basename(dirpath)
return '', empty string. in case, basename(dirname('a/b/c/'))
return 'c'.
from os.path import basename, dirname import openpyxl def crearlista (*arg, **kw): inventario = openpyxl.workbook(encoding = "utf-8") sheet = inventario.active = 1 dirpath, subdirs, files in os.walk("//media//rayeus/datos/mis documentos/nueva carpeta/", topdown=false): file_dir = basename(dirpath) or dirname(basename(dirpath)) name in files: sheet.cell(row=i, column=1).value = dirpath sheet.cell(row=i, column=2).value = file_dir sheet.cell(row=i, column=3).value = name += 1
Comments
Post a Comment