Using os.walk in Python 3.10
My code
import os
def generate_dir_report(path, report_file_path):
print("n ---- Starting generate_dir_report ----")
# open file
f = open(report_file_path, "w")
for root, dirs, files in sorted(os.walk(path)):
for file_name in sorted(files):
# write the `root` string into the `out` file as a single line>
# fix print(root)
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")
f.close()
print(" ---- Done ----n")
generate_dir_report('data/dir-top','dir-report.txt')
Expected results
data/dir-top
file1.txt
file2.txt
data/dir-top/dir1
file3.txt
data/dir-top/dir2
file6.txt
file7.log
data/dir-top/dir3
file4.log
data/dir-top/dir3/dir4
file5.txt
Actual result
---- Starting generate_dir_report ----
data/dir-top
file1.txt
file2.txt
data/dir-top
file1.txt
file2.txt
data/dir-top/dir1
file3.txt
data/dir-top/dir2
file6.txt
file7.log
data/dir-top/dir2
file6.txt
file7.log
data/dir-top/dir3
file4.log
data/dir-top/dir3/dir4
file5.txt
---- Done ----
The first expected entry (first 3 lines) seem to be duplicated 2x in my actual results. The same happens again so that the total expected lines are 12 and the total actual lines are 18.
I have duplicated the issue on Windows, and a web-based virtualization I am using; the results are consistent in both cases.