Use
This could not work, because the quote is escaped by the last
To know if a file has only white spaces inside, you have to read the whole file. This is a big problem, if there are big files. So you need to have a limit for this. Then you could read the files, which are small enough, stripping them and when the result is an empty str/bytes, then delete the file.
The annotations are not mandatory, but they give the programmer an Idea which types should be used.
There is no control, if the right types are used. This is for example if you use an IDE and you want to give the
IDE better hints. So, you'll use this in future at some point.
Code:
pathlib.Path
for better abstraction.This could not work, because the quote is escaped by the last
\
.path = 'C:\Path\to\folder\'Better:
path = r'C:\Path\to\folder'raw-string, so escape don't work, only the quote
'
/"
could be escaped.sys.exit
is not required at the end, because if there is only the Main-Thread and there are no further statements and no loop, the program ends.To know if a file has only white spaces inside, you have to read the whole file. This is a big problem, if there are big files. So you need to have a limit for this. Then you could read the files, which are small enough, stripping them and when the result is an empty str/bytes, then delete the file.
The annotations are not mandatory, but they give the programmer an Idea which types should be used.
There is no control, if the right types are used. This is for example if you use an IDE and you want to give the
IDE better hints. So, you'll use this in future at some point.
Code:
#!/usr/bin/env python3 from __future__ import annotations from pathlib import Path ONE_MIB = 1048576 def remove_empty(root: str | Path, max_size: int = ONE_MIB) -> None: """ Removes all files, which are 0 bytes big Removes all files, which are smaller or equal than max_size and have only whitespace inside. This prevents striping files which are too big (takes time to read into memory and stripping) """ root = Path(root) for path in root.rglob("*"): if not path.is_file(): # we want only real files # path could also be a directory continue size = path.stat().st_size # if size == 0, unlink # or if size is smaller as max_size, then read the whole content of file into # memory, stripping whitespace. Empty bytes/str is False if size == 0 or size <= max_size and not path.read_bytes().strip(): path.unlink() if __name__ == "__main__": path = r"C:\Path\to\folder" # path had a backslash at the end, which excapes the qoute. # This is also for raw-strings True remove_empty(path)I like it to use double quotes, because I can see them better.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
All humans together. We don't need politicians!