Home > Back-end >  Python how to check if there is file under a folder at the same level of a subfolder
Python how to check if there is file under a folder at the same level of a subfolder

Time:09-29

The folder structure is like this,under Main folder there may have some files at the same leave as Subfolder:

Main folder --
            file1.xlsx
            file2.xlsx
            Subfolder

How to check is there any file under Main folder at the same level of Subfolder ?

I used:

 os.path.exists(Main folder)

But even there is no any file ,just Subfolder there ,it will return True, is there any way can tell there is no file under Main folder at the same level of Subfolder ,just Subfolder there ?

CodePudding user response:

If you want to check if a folder contains files use: os.listdir( path ) This will return a list containing the filenames of a directory. Your function returns true if simply the path exists, which always returns true if the folder is already present.

CodePudding user response:

You can use absolute path os.path.abspath to get absolute path of the file and move back n times. To get to the level of Main folder (n=2) you can use

back_2 = '/'   ('../'*2)
pth = os.path.abspath(__file__   back_2)
os.path.exists(f"{pth}/Main folder")
  • Related