FileNotFoundError: [WinError 2] The system cannot find the file specified: find extensions in os.listdir

46 Views Asked by At

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' ?

1

There are 1 best solutions below

1
Shmack On

If you are not bound to the os module, I would encourage you to use the Path class from pathlib. It is more readable in my opinion, which makes it feel less clunky.

from pathlib import Path

# assuming zip_path = Path("path/to/zip_file_you_dont_want_to_delete.zip")
zip_path_parent = zip_path.parent

# delete files from the save path but preserve the zip file
for file in zip_path_parent.glob("*.*"):
    if file.is_file():
        if file.suffix != ".zip":
            file.unlink()

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"