Trying to delete all but one file in a given directory. Looked at other related posts but my question seems specific to getting names from os.listdir and needing full path with extensions to use os.remove:
# delete files from the save path but preserve the zip file
if os.path.isfile(zip_path):
for clean_up in os.listdir(data_path):
if not clean_up.endswith(tStamp+'.zip'):
os.remove(clean_up)
Gives this error:
Line 5: os.remove(clean_up)
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'firstFileInListName'
I think this is because os.listdir is not capturing the file extension of each file (printed os.listdir(data_path) and only got names of the files without extensions)
What can I do to delete all files from the data_path except for the one that ends with tStamp+'.zip' ?
If you are not bound to the
osmodule, I would encourage you to use thePathclass frompathlib. It is more readable in my opinion, which makes it feel less clunky.It has several methods that are also super helpful for replacing or getting components of the path, if need be, for instance:
file.stem-> outputs "some_file.some_extension"file.suffix-> outputs ".some_extension"file.name-> output "some_file"file.with_stem('some_new_file_name')-> outputs "some_new_file_name.some_extension"file.with_suffix('.txt')-> outputs "some_file.txt"file.with_name("new_file.txt")-> outputs "some/path/new_file.txt"