-1

I have a few files with this format:

17-07-39_03-05-2022_Testing.txt 
16-07-34_03-05-2022_Testing.png

"Testing" is the name of the system. I am trying to use subprocess to delete all files that have "Testing" in them at the end.

pc_user = subprocess.run("whoami", capture_output=True, shell=False).stdout.decode().strip("\n")
name, user = pc_user.split("\\")

path = f"C:/Users/Testing/PycharmProjects/pythonProject/Project/"
subprocess.run(f"rm {path}*{name}.*")
martineau
  • 119,623
  • 25
  • 170
  • 301
Oakzeh
  • 35
  • 8
  • 2
    Why are you using `subprocess` (which incurs a major overhead) when Python could do the work for you with functions from `os` and perhaps `pathlib` or `shutil`? If you need to use `subprocess` why didn't you include `"Testing"` at the end of the expression with wildcards in the `"rm"` command? – Grismar May 03 '22 at 08:30
  • what does this have to do with powershell? the `whoami` command is a CMD/BAT command, not powershell. – Lee_Dailey May 03 '22 at 09:18

2 Answers2

1

(OP has edited the question since this was posted and removed the powershell tags, making this answer irellevant)

There is a much simpler way to do this using Get-ChildItem and a -like using only powershell.

foreach($file in (gci -path "C:/Users/Testing/PycharmProjects/pythonProject/Project/")){ if($file.name -like "*testing.*"){ remove-item $file.fullname -confirm:$false }}
Panomosh
  • 884
  • 2
  • 8
  • 18
  • thanks this could be a viable solution I am trying to use the sub process module and run it through a python script – Oakzeh May 03 '22 at 12:52
1

I would use a slightly different approach to delete these specific files.

First, you will want to make a list of the paths to all files. It should look like this:

list = ['17-07-39_03-05-2022_Testing.txt', 
        '16-07-34_03-05-2022_Testing.png',
       etc.]

Then, you want to search this list for paths that include the string 'testing' and put all these paths in a new list:

testing_list = []
for path in list:
    if path.find('Testing') > 0:
        testing_list.append(path)

You can now delete all files in the testing_list list. I would use one of the following methods:

  • os.remove() removes a fil
  • os.rmdir() removes an empty directory.
  • shutil.rmtree() deletes a directory and all its contents.

You can find more information on deleting files here

NotARobot
  • 49
  • 2
  • thanks, I have thought about using os I know that would work appending to lists then removing it. but I was told not to use os any more as it has been redacted and sub process is the best alternative. thoughts? – Oakzeh May 03 '22 at 12:54