Check if a file exists within a Python IF

Asked

Viewed 1,150 times

0

Good afternoon, I’d like to make a check: If a file exists - delete
If there is no following the flow of the program.

I’m using Pycharm, you’re returning syntax error,
But I’ve already put four spaces in the bottom line.
Obs The rest of the code is commented.

Print do codigo.

Follows the code:

import os  
import os.path

str(input("Digite Enter Para continuar01"))

if os.path.exists('TM.ext'):
    os.remove("TM.txt")
else:
    print("Arquivo nao existe")
  • Mark, the code you are using is the one in the photo ? or the one you put in text ? the photo is full of typing errors , but the text of the post seems well identado. Which of the two refers ?

  • The code you present this one way, but the image of another, in the image missing the two points in the line of if

  • @Otávioreisperkles edited the question, I may have corrected the identation, it was badly formatted tb.

  • 2

    @Sidon The two points after the if and of else were added in Revision 2, which may have been a misconception, because they are the cause of the syntax error, and by putting them, mischaracterized the question, because now the error no longer occurs.

  • It is actually the kind of question that could be avoided if the user had taken care of while asking the question. :-)

  • My last comment became almost a recursion. :-)

Show 1 more comment

2 answers

2

Note that you are not putting : on the lines of if and of else and also if the path for a folder os.path.exists() will return True and os.remove() will make a mistake.

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

import os  

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

Or you can delete without testing if the file exists and captures the Oserror the module will launch. Ex.:

import os

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

Repl.it with the code working


Edit

So there’s nothing implied where I got the Oserror.

In the documentation of the module 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 of this module launch Oserror in case of invalid or inaccessible file names or paths ...

0

uses this command is what I use in my cods:

import os.path



if os.path.isfile('arquivo.txt'):
    print("é arquivo") 
  • 1

    With this code, an error will be generated, missing the two dots in the if line. Edit your answer.

  • thank you. keyboard ate rsss

Browser other questions tagged

You are not signed in. Login or sign up in order to post.