In the code below, commenting or uncommenting this line
`tmp_string = dirs[0]’ produces the error
Traceback (most recent call last):
File "C:Users<pathwip_python_filesdef generate_dir_report_fn.py", line 60, in <module>
generate_dir_report('data/dir-top','dir-report.txt')
File "C:Users<path>wip_python_filesdef generate_dir_report_fn.py", line 32, in generate_dir_report
tmp_string = dirs[0]
IndexError: list index out of range
Code
import os
def get_path_depth(path):
path = os.path.normpath(path)
return len(path.split(os.sep))
print(get_path_depth('dir1'))
def generate_dir_report(path, report_file_path):
print("n ---- Starting generate_dir_report ----")
# open file
f = open(report_file_path, "w")
main_path_depth = get_path_depth(path)
print("mpd =",main_path_depth,"n")
# get the name of the base directory, printed later
os_path_basename = os.path.basename(path)
print("+ " + os_path_basename)
#
loop_count = 0
temp_len = 0
for root, dirs, files in sorted(os.walk(path)):
# store variable `dir_indent` which you can compute as <depth of the root> - `main_path_depth` - 1
# print("type is ",type(dirs[loop_count]), dirs[loop_count])
# dir_indent = get_path_depth('dir1')
# print("dir_indent",dir_indent)
# dir_indent = get_path_depth(dirs[loop_count])
#print(dirs[1])
## ------------------------------------------------------
## comment or uncomment line below to reproduce the error
## -----------------------------------------------------
# tmp_string = dirs[0]
tmp_string = dirs[0]
# temp_len = get_path_depth(str(tmp_string))
dir_indent = 1
print("dir_indent = ",dir_indent,"loop_Count = ",loop_count)
# store variable `file_indent` which you can compute as `dir_indent` + 1
# write the `root` string into the `out` file as a single line>
if(loop_count != 0):
print("|-+ " + root)
f.write("!-+ " + root + "n")
# write the `root` string into the `out` file as a single line>
for file_name in sorted(files):
# write the `file_name` string into the `out` file as a single line
print(file_name)
f.write(file_name + "n")
loop_count = loop_count + 1
# break
f.close()
print(" ---- Done ----n")
generate_dir_report('data/dir-top','dir-report.txt')
Inserting a break after the line, uncommenting no longer causes the error.
Variable `dirs1 is a list, element 0 should exist.