Delete all files from directory windows

Remove all files in a directory

Trying to remove all of the files in a certain directory gives me the follwing error:

OSError: [Errno 2] No such file or directory: ‘/home/me/test/*’

The code I’m running is:

13 Answers 13

os.remove() does not work on a directory, and os.rmdir() will only work on an empty directory. And Python won’t automatically expand «/home/me/test/*» like some shells do.

You can use shutil.rmtree() on the directory to do this, however.

be careful as it removes the files and the sub-directories as well.

os.remove doesn’t resolve unix-style patterns. If you are on a unix-like system you can:

Bit of a hack but if you would like to keep the directory, the following can be used.

Because the * is a shell construct. Python is literally looking for a file named «*» in the directory /home/me/test. Use listdir to get a list of the files first and then call remove on each one.

Although this is an old question, I think none has already answered using this approach:

This will get all files in a directory and remove them.

star is expanded by Unix shell. Your call is not accessing shell, it’s merely trying to remove a file with the name ending with the star

shutil.rmtree() for most cases. But it doesn’t work for in Windows for readonly files. For windows import win32api and win32con modules from PyWin32.

os.remove will only remove a single file.

In order to remove with wildcards, you’ll need to write your own routine that handles this.

There are quite a few suggested approaches listed on this forum page.

Another way I’ve done this:

Please see my answer here:

It’s a long and ugly, but reliable and efficient solution.

It resolves a few problems which are not addressed by the other answerers:

Delete all files of specific type (extension) recursively down a directory using a batch file

I need to delete all .jpg and .txt files (for example) in dir1 and dir2.

What I tried was:

In some directories it worked; in others it didn’t.

For example, this didn’t do anything:

What I’m I missing in the second snippet? Why didn’t it work?

6 Answers 6

You can use wildcards with the del command, and /S to do it recursively.

Addendum

@BmyGuest asked why a downvoted answer ( del /s c:\*.blaawbg ) was any different than my answer.

There’s a huge difference between running del /S *.jpg and del /S C:\*.jpg . The first command is executed from the current location, whereas the second is executed on the whole drive.

In the scenario where you delete jpg files using the second command, some applications might stop working, and you’ll end up losing all your family pictures. This is utterly annoying, but your computer will still be able to run.

Читайте также:  Как включить поддержку trim mac os

However, if you are working on some project, and want to delete all your dll files in myProject\dll , and run the following batch file:

Then you end up removing all dll files form your C:\ drive. All of your applications stop working, your computer becomes useless, and at the next reboot you are teleported in the fourth dimension where you will be stuck for eternity.

The lesson here is not to run such command directly at the root of a drive (or in any other location that might be dangerous, such as %windir% ) if you can avoid it. Always run them as locally as possible.

How can I delete all files/subfolders in a given folder via the command prompt?

I would like to delete all files and subfolders in a batch file in Windows 7 and keep the top folder. Basically emptying the folder. What’s the command line instruction for that?

17 Answers 17

You can do this using del and the /S flag (to tell it to remove all files from all subdirectories):

The best Solution: e.g. i want to delete all files and sub-directories of parent directory lets say «C:\Users\Desktop\New folder\». The easy way is create batch file of below three commands.

rmdir /S /Q «C:\Users\Desktop\New folder\»

Here first it will clean all files in all sub-directories and then cleans all empty sub-directories. Since current working directory is parent directory i.e.»\New folder», rmdir command can’t delete this directory itself.

Navigate to the parent directory:

Delete the sub folders:

you can use rmdir to delete the files and subfolder, like this:

However, it is significantly faster, especially when you have a lot of subfolders in your structure to use del before the rmdir, like this:

Don’t forget to use the quotes and for the /q /s it will delete all the repositories and without prompting.

You can do it quickly and easily by putting these three instructions in your bat file:

If you want to delete all files in a folder, including all subfolders and not rely on some error conditions to keep the root folder intact (like I saw in another answer) you could have a batch file like this:

And then you would simply call it with:

user340956 was painfully close to the solution, but you know what they say about close…

To be clear, rd /s /q c:\foobar deletes the target directory in addition to its contents, but you don’t always want to delete the directory itself, sometimes you just want to delete its contents and leave the directory alone. The deltree command could do this, but Micrsoft, in its infinite «wisdom» removed the command and didn’t port it to Windows.

Here’s a solution that works without resorting to third-party tools. It’s probably about as simple and efficient as is possible with a command-line script instead of outright writing an actual executable. It doesn’t set any environment variables and it doesn’t use any loops. It’s also as safe as can be, with error-checking everywhere possible, and also as user-friendly as possible, with built-in docs.

dt.bat (or dt.cmd for the kids; whatever, I’m old, I use .bat 🤷):

Here’s how it works:

  1. It checks if a command-line argument has been passed, and prints usage information and quits if not.
  2. It uses pushd to save the current directory, then switch to the target directory, redirecting any errors to nul for a cleaner command-line experience (and cleaner logs).
  3. It checks to see if the current directory is now the same as the target directory, and prints an error message and quits if it is not. This avoids accidentally deleting the contents of the previous directory if the pushd command failed (e.g., passing an invalid directory, access-error, etc.)
    • This check is case-insensitive, so it’s usually safe on Windows, but isn’t for any case-sensitive file-systems like those used by *nix systems, even under Windows.
    • It doesn’t work with short-filenames (e.g. C:\Users\Bob Bobson\foobar won’t be seen as being the same as C:\Users\BobBob

1\foobar even if they actually are). It’s a slight inconvenience to have to use the non-short filename, but it’s better safe than sorry, especially since SFNs aren’t completely reliable or always predictable (and may even be disabled altogether).

  • It then uses rd to delete the target directory and all of its contents, redirecting any errors (which there should be at least one for the directory itself) to nul . Some notes about this:
    • Because the target directory is the current directory, the system has an open file-handle to it, and thus it cannot actually delete it, so it remains as is, which is the desired behavior.
    • Because it doesn’t try to remove the target directory until after its contents have been removed, it should now be empty (other than anything that also has open file handles).
  • Finally, it uses popd to return to the previously-current directory and ends the script.
  • (If you like, you can comment the script with the above descriptions using rem or :: .)

    Delete all files from a folder and its sub folders

    I want to remove all files from a folder structure, so I’m left with an empty folder structure.

    Can this be achieved in either batch or VBScript scripting?

    I have tried a very basic batch command, but this required the user to allow the deletion of each file. This wasn’t a suitable solution as there are many hundreds of files and this will increase massively over time.

    What can you suggest?

    14 Answers 14

    This can be accomplished using PowerShell:

    This command gets each child item in $path , executes the delete method on each one, and is quite fast. The folder structure is left intact.

    If you may have files without an extension, use

    It appears the -File parameter may have been added after PowerShell v2. If that’s the case, then

    It should do the trick for files that have an extension.

    Short and sweet PowerShell. Not sure what the lowest version of PS it will work with.

    You can do so with del command:

    The /S switch is to delete only files recursively.

    Reading between the lines on your original question I can offer an alternative BATCH code line you can use. What this will do when ran is only delete files that are over 60 days old. This way you can put this in a scheduled task and when it runs it deletes the excess files that you don’t need rather than blowing away the whole directory. You can change 60 to 5 days or even 1 day if you wanted to. This does not delete folders.

    Use PowerShell to Delete a Single File or Folder. Before executing the Delete command in powershell we need to make sure you are logged in to the server or PC with an account that has full access to the objects you want to delete.

    Using PowerShell commnads to delete a file

    Remove-Item -Path «C:\dotnet-helpers\DummyfiletoDelete.txt»

    The above command will execute and delete the “DummyfiletoDelete.txt” file which present inside the “C:\dotnet-helpers” location.

    Using PowerShell commnads to delete all files

    Using PowerShell commnads to delete all files and folders

    -recurse drills down and finds lots more files. The –recurse parameter will allow PowerShell to remove any child items without asking for permission. Additionally, the –force parameter can be added to delete hidden or read-only files.

    Using -Force command to delete files forcefully

    Using PowerShell command to delete all files forcefully

    How to delete all files and folders in a folder by cmd call

    I want to delete all files and folders in a folder by system call.

    I may call like that:

    Do you know an easier way?

    12 Answers 12

    No, I don’t know one.

    If you want to retain the original directory for some reason (ACLs, &c.), and instead really want to empty it, then you can do the following:

    This first removes all files from the directory, and then recursively removes all nested directories, but overall keeping the top-level directory as it is (except for its contents).

    Note that within a batch file you need to double the % within the for loop:

    del c:\destination\*.* /s /q worked for me. I hope that works for you as well.

    I think the easiest way to do it is:

    The last «\» in the path is the important part.

    Yes! Use Powershell:

    If the subfolder names may contain spaces you need to surround them in escaped quotes. The following example shows this for commands used in a batch file.

    To delete folder with all files in it:

    To delete all files from specific folder (not deleting folder itself) is a little bit complicated. del /s *.* cannot delete folders, but removes files from all subfolder. So two commands are needed:

    You can create a script to delete whatever you want (folder or file) like this mydel.bat :

    Few example of usage:

    One easy one-line option is to create an empty directory somewhere on your file system, and then use ROBOCOPY (http://technet.microsoft.com/en-us/library/cc733145.aspx) with the /MIR switch to remove all files and subfolders. By default, robocopy does not copy security, so the ACLs in your root folder should remain intact.

    Also probably want to set a value for the retry switch, /r , because the default number of retries is 1 million.

    I had an index folder with 33 folders that needed all the files and subfolders removed in them. I opened a command line in the index folder and then used these commands:

    I separated them into two lines (hit enter after first line, and when asked for more add second line) because if entered on a single line this may not work. This command will erase each directory and then create a new one which is empty, thus removing all files and subflolders in the original directory.

    Читайте также:  Все видеоредакторы для linux
    Оцените статью