Python os is not working

I have Written This Code

import os
filename = r"File_path"
print("size of file is byte = {} byte".format(os.path.getsize(filename)))
print("size of file is in MB = {} MB".format(os.path.getsize(filename) >> 20))

And I Am Getting This error

Traceback (most recent call last):
  File "d:\Vs code\Python Flask\Flask Projects\Movie-Giver-Website-App\Test\vidSize.py", 
line 6, in <module>
    print("size of file is byte = {} byte".format(os.path.getsize(filename)))
  File "C:\python 39\lib\genericpath.py", line 50, in getsize
    return os.stat(filename).st_size
FileNotFoundError: [WinError 2] The system cannot find the file specified

Why?..

Thank you for this excellent post, including code and output. Very
welcome.

I know this will sound trite, but this will be because there’s no file
named File_path in the directory where you are running the python
script.

Add this before the print statements:

print(os.getcwd())

and see what it says. Is that where you expect File_path to exist?

When you use a “relative” filename like File_path it is sought in the
current working directory, returned by os.getcwd() above.

I also see from your traceback that you’re on windows. If this line:

filename = r"File_path"

is in fact a placeholder for some real path on your system which you’re
using in reality, check that the real path in your code is also
specified as a “raw” string. You’re line:

filename = r"File_path"

is a raw string. It is important to use the r"…" syntax with Windows
paths because the Windows path separator “” is also important
punctuation in Python non-“raw” strings. So this is a recommended form:

filename = r"C:\Users\name\some\path\here"

Were this written as an ordinary Python string:

filename = "C:\Users\name\some\path\here"

The the “\n” in “\name” would be turned into a newline character, no
what you intended.

Finally, you have this:

print("size of file is in MB = {} MB".format(os.path.getsize(filename) >> 20))

Technically that computes “mebibytes” (2^20, per your “>>20” bit shift),
whose abbreviation is “MiB”, not “MB” which is supposed to be
“megabytes” (10^6). Just a notation issue. See this:

https://en.wikipedia.org/wiki/Byte#Multiple-byte_units

Cheers,
Cameron Simpson cs@cskk.id.au

1 Like