How can I check If a file exists or not in Python 3?

Dung Do Tien May 11 2022 399

Hello Guys, I have written an application using Python to help read log files (txt files). Sometimes run code I got an exception file not found. My code is like this:

 datas = []
with open('iis-apache-logs.txt') as f:
    datas = f.readlines()

i = 0
for row in datas:
    i += 1
    print(f'{i}: {row}')  

My question is how to check If a file exists or not in Python? 

Thanks in advance.

Have 2 answer(s) found.
  • P

    P May 11 2022

    To check whether a file has existed or not. I usually use os.path.exists() function to check. Like this:

     import os.path
    file_exists = os.path.exists('log-20220501.txt')
    if file_exists:
      print("Not Existed")

    I hope this answer is useful for you.

  • B

    Basly Rahma May 11 2022

    Easy way to use pathlib.Path.exists(path) function. This function will return a true/false value. Like this:

     from pathlib import Path
    file_exists = Path('test-log.txt')
    if file_exists.exists ():
      print("Not Existed")
Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close