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}.*")
CodePudding user response:
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
CodePudding user response:
(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 }}