I am trying to check if 3 files exist in a directory in a recursive way. If one (or all of the files) does not exist, it will write a file in the respective directory.
I found some posts that explian how to do it, as for example here How to recursively go through all subdirectories and read files?
However, the files I want to write should only be written in certain directories. Imagine a diretory structure with three levels. And I want to check and write the files only in the third level.
I tried the following code:
name1 = 'Info_1_250.csv'
name2 = 'Info_1_500.csv'
name3 = 'Info_1_1000.csv'
path_name = '/Users/user/Desktop/test/'
for root, _, files in os.walk(path_name):
if name1 not in files:
write_file(os.path.join(root, name1))
elif name2 not in files:
write_file(os.path.join(root, name2))
elif name3 not in files:
write_file(os.path.join(root, name1))
write_file is a function that I wrote that will write the file.
The problem is that this code write the file "name1" in all directories if it does not exist. It even writes in the top level and 2nd level directories (which I don't want). However in the top level and 2nd level, it only writes the file "name1". The other two files, even though it does exist, it is not written.
Finally, if the three files are missing from a specific directory in level3, all three files should be written. I only would like files to be written in level3.
In other words, I want to turn the following tree:
/a
/a/b
/a/b/c
/a/b/d
/a/e
/a/e/f
/a/e/f/Info_1_250.csv
/a/e/g
/a/e/g/Info_1_500.csv
/h
/h/i
/h/i/j
/h/i/j/Info_1_500.csv
/h/i/j/Info_1_1000.csv
Into the following:
/a
/a/b
/a/b/c
/a/b/c/Info_1_250.csv
/a/b/c/Info_1_500.csv
/a/b/c/Info_1_1000.csv
/a/b/d
/a/b/d/Info_1_250.csv
/a/b/d/Info_1_500.csv
/a/b/d/Info_1_1000.csv
/a/e
/a/e/f
/a/e/f/Info_1_250.csv
/a/e/f/Info_1_500.csv
/a/e/f/Info_1_1000.csv
/a/e/g
/a/e/g/Info_1_250.csv
/a/e/g/Info_1_500.csv
/a/e/g/Info_1_1000.csv
/h
/h/i
/h/i/j/Info_1_250.csv
/h/i/j/Info_1_500.csv
/h/i/j/Info_1_1000.csv
As you can see, for every third-level directory in the tree, the files Info_1_250.csv
, Info_1_500.csv
and Info_1_1000.csv
must be created when missing. The other directories must be left untouched.