i have an script that deletes all csv files exept 2 types. I have one file that i can't delete and i tried to delete it but it just doesn't work, even to i am the admin. So my script needs to skip this File. But it prints the Error and stops running. Hope you can help me.
import os
try:
for rootDir, subdir, files in os.walk("Z:"):
for filenames in files:
if filenames.endswith((".csv")) and not filenames.endswith(("LBL.csv")) and not
filenames.endswith(("Code.csv")):
foundfiles = os.path.join(rootDir, filenames)
os.remove(os.path.join(rootDir, filenames))
except Exception as e:
print(e)
CodePudding user response:
At first you can split your filename and extension better with the function. Try this below
import os
try:
for root, subdir, files in os.walk("..."):
for file in files:
name, extension = os.path.splitext(file)
if extension == ".csv" and name != "..." and name != "...":
try:
found_file = os.path.join(root, file)
os.remove(found_file)
except Exception as e:
print(e)
except Exception as e:
print(e)
CodePudding user response:
Ok thanks for the fast input. But your code @multimoehre deleted the 2 types that i want to keep. Code.csv or LBL.csv isn't the full name of these files, they just end like that. So a mix of my and your code was the solution. Thank you.
try:
for root, subdir, files in os.walk("Z:"):
for filenames in files:
if filenames.endswith((".csv")) and not
filenames.endswith(("LBL.csv")) and not
filenames.endswith(("Code.csv")):
try:
oundfiles = os.path.join(root, filenames)
os.remove(os.path.join(root, filenames))
except Exception as e:
print(e)
except Exception as e:
print(e)