B
B
Bogdan01102021-07-21 23:51:55
Python
Bogdan0110, 2021-07-21 23:51:55

How to check the presence of a given file in a given directory using os.listdir()?

Hello, there is a main.py file in the Project folder. In this folder besides main.py there are various other files (.txt, .jpg, .mp3 etc ), how can I check if a given file is in this folder/directory using sys.argv[0] and os.listdir () . That is, if my file (main.py) is present in this folder, then display "yes", otherwise "no" (check with an if-else loop)
Thanks in advance....

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vindicar, 2021-07-22
@Bogdan0110

Something like this. The resolve() method is needed to deal with elements like .. and symbolic links, and get absolute paths.

from pathlib import Path
target_path = ... #определяешь целевой путь

if Path(sys.argv[0]).parent.resolve() == Path(target_path).resolve():
    print('Тот же путь!') #оба пути указывают на один каталог

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question