Check if a file exists, inside an IF in Python [closed]

0

Good afternoon, I would like to do a verification: If a file exists - delete
If there is no follow the flow of the program.

I'm using Pycharm, it's returning syntax error,
But I've already put 4 spaces in the bottom line. Note The rest of the code is commented.

Followthecode:

importosimportos.pathstr(input("Digite Enter Para continuar01"))

if os.path.exists('TM.ext'):
    os.remove("TM.txt")
else:
    print("Arquivo nao existe")
    
asked by anonymous 05.12.2018 / 17:33

2 answers

2

Note that you are not putting : on the lines of if and else and also if path is a folder os.path.exists() will return True and os.remove() will throw an error.

You can test whether the file exists with os.path.isfile() , and if there is remove with os.remove . Ex.:

import os  

if os.path.isfile('TM.ext'):
    os.remove("TM.txt")

Or you can delete without testing whether the file exists and capture OSError than the module will launch. Ex.:

import os

try:
    os.remove("TM.txt")
except OSError:
    pass

Repl.it with the working code

Edit

In order to get nothing implicit from where I took the OSError .

At the module documentation os is specified at the top:

  

Note :   All functions in this module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type, but are not accepted by the operating system.

Translating:

  

Note :   All functions in this module launch OSError for invalid or inaccessible file names or paths. .

    
05.12.2018 / 18:03
0

Use this command is what I use in my cods:

import os.path



if os.path.isfile('arquivo.txt'):
    print("é arquivo") 
    
05.12.2018 / 17:40