-1

I have folder 201 and subfolder 202 then some files in the 202 folder. Now i want to check in folder 201 if files exist but it always shows yes as there's sub-folder (202).

201 folder has no files and 202 have 3 files.

There is not a single file folder 201 but below code prints " files found in the directory."

import os

p = r"C:\sample_test\201"

for files in os.walk(p):
    if files:
        print(p, " files found in the directory.")
    if not files:
        print(p, " files NOT found in the directory.")
Nick
  • 15
  • 4

1 Answers1

0

You can use os.listdir and os.path.isfile:

import os

p = r"C:\sample_test\201"
has_files = any(fse for fse in os.listdir(p) if os.path.isfile(fse))
enzo
  • 9,861
  • 3
  • 15
  • 38
  • for p = r"C:\sample_test\201" got result "False" and for p = r"C:\sample_test\201\202" also got same result "False". I was expecting "True" for p = r"C:\sample_test\201\202". – Nick Jul 20 '21 at 15:27
  • I have parquet files in 202 folder, Is it why Isfile function not recognising as it is flat file? – Nick Jul 20 '21 at 15:41
  • test using the whole path it is working (got TRUE value) for individual file with Isfile(). but in above code if i use as only file name with extension it gives me "False". – Nick Jul 20 '21 at 15:54
  • Got it finally. below code worked. a = str(p+"\\") has_files = any(fse for fse in os.listdir(p) if os.path.isfile(a+fse)) – Nick Jul 20 '21 at 16:30