Delete files with Python

2

I'm trying to make a bash adaptation (the Linux terminal) in Windows, for this I'm using Python.

#-*- coding: utf-8 -*-
import subprocess
import os
if __name__ == '__main__':
    wt = True
    while wt:
        cmd = str(raw_input("{}>".format(os.getcwd())))
        if cmd == "help":
            print('''de momento no pondré este comando porque el output es largo''')
        elif cmd == "clear":
            subprocess.call(["cmd.exe","/c","cls"])
        elif cmd [:2] == "ls" and cmd[2:] == "":
            dirlist = os.listdir('.')

            for file in dirlist:
                print(file)

        elif cmd[:6] == "mkdir ":
            try:
                os.mkdir(cmd[6:])
            except Exception as e: 
                print("ese directorio ya existe") 
        elif cmd[:3] == "cd ":
            try:
                os.chdir(cmd[3:])
            except Exception as e:
                print("el sistema no puede encontrar la ruta")
        elif cmd[:3] == "rm":
            pass    

The problem is in the rm command, I just do not know how to do it. I thought about putting subprocess.call(["cmd.exe","/c","del (archivo)"]) but it was going to complicate me anyway, because in batch (cmd) files and directories are deleted with different commands, then I would have to make the program identify if it is a directory or a file.

How can I delete files with python?

O

How can I make Python distinguish if something is a file or a directory?

Any of the 2 answers will be useful, thanks

    
asked by binario_newbie 27.03.2018 в 01:12
source

2 answers

1

From what I understand, you are looking to implement a fairly limited functionality of the rm command, basically deleting a file and not a folder. You could implement something like this:

import os
import sys

def rm(path):

    if os.path.isdir(path):  
        print("Imposible borrar {0}!. Es una carpeta.".format(path))  
    elif os.path.isfile(path):  
        try:
            os.remove(path)
        except OSError, e:
            print ("Error: %s - %s." % (e.filename,e.strerror))

    else:  
        print("Error. No se ha encontrado {0}.".format(path))  

To prove it:

file_to_delete=raw_input("Ingrese el archivo a borrar: ")
rm(file_to_delete)

Detail:

  • With os.path.isdir() we determine if the path entered corresponds to a folder / directory
  • With os.path.isfile() if it is a file, in which case:
  • os.remove() will delete it. Note that we use a try/except clause to handle any exception of OSError .

In practice os.remove() will issue an exception of type OSError to% try to delete a folder, so we could avoid controlling if it is a directory and simplify the function even more:

def rm(path):

    try:
        os.remove(path)
    except OSError, e:
        print ("Error: %s - %s." % (e.filename,e.strerror))
    
answered by 27.03.2018 / 04:56
source
2

Python has methods to perform these tasks, such as remove and rmdir

you also have useful functions like:

In general, I recommend you take a look at the standard library documentation os , and remember the difference between the windows and linux directories '/' and '\'. use the functions of os.path to that you avoid problems.

also os.path has functions to determine if a path is a directory, a file or a link ( isdir, isfile, islink )

    
answered by 27.03.2018 в 01:22