Im trying to make lines of code where it checks if a file with a name like "text1.txt" exists in a directory. If it exists it will proceed to run the program, if it doesnt it will do something else.
Asked
Active
Viewed 97 times
3 Answers
0
you can use pathlib2 library
from pathlib2 import Path
if (Path(".") / <YOUR_FILE_NAME_.txt>).exists():
do your stuff here
Assuming you run your python code from your directory

sslloo
- 521
- 2
- 10
0
You can use the os builtin module. Check here: https://docs.python.org/3/library/os.html
basically you can try something like this, keep in mind that if the directory containing the file is not the cwd, you will need to provide the full path to the file.
import os
os.path.exists('<filename>')

osmay88
- 421
- 3
- 12
0
If you're already using pathlib
, you can just use .exists()
on a Path.

Bram Vanroy
- 27,032
- 24
- 137
- 239