i have a no-extension file in path: C:/Users/example/Downloads. the file name is examplefile, so path will be C:/Users/example/Downloads/examplefile. i tried to use
os.stat("C:/Users/example/Downloads/examplefile").st_size
but i got this error:
File "<pyshell#26>", line 1, in <module>
os.stat(file).st_size
FileNotFoundError: [WinError 2] The specified file could not be found: 'C:/Users/example/Downloads/examplefile'
so i tried using os.path.getsize()
but i still got the same error.
How can i get file size?
The file does have an extension in this case - it is just windows that does not show it in the default configurations.
You can gt the real file name from Python by using a glob-pattern when trying to get to it.
As a convenience, you might want to use the pathlib
, instead of os
, as it will combine glob functionality and stat in a single place:
from pathlib import Path
path_to_guess = Path("C:/Users/example/Downloads/examplefile")
path = path_to_guess.parent.glob(path_to_guess.stem + ".*")[0]
print(path)
# here you have the extension. Of course, you might have more than one
# file with the same base name- this is good for a
# one time script or interactive use -
# for production you should check also creation time, and maybe use
# other means to pick the correct file.
size = path.stat.st_size()