0

I am a python newbie and learning from "automate boring stuff" book, so it says in the book the I can use os.path.getsize(path) to get a file size but when I run this code it gives an error, can you please explain why I am getting this?

import os

mypath = 'C:\\Users\\C2D\\Desktop\\Embedded system\\u1.PNG'
os.chdir(mypath)
print(os.path.getsize(mypath))

error is : NotADirectoryError: [WinError 267] The directory name is invalid: 'C:\Users\C2D\Desktop\Embedded system\u1.PNG'

I am working on windows 8.1 and using python3.8 on pycharm

mr.Arrow
  • 49
  • 5
  • 1
    The error is happening in `os.chdir()`. `u1.PNG` is a file, the argument to `os.chdir()` has to be a directory. – Barmar Apr 06 '20 at 22:26
  • Didn't the traceback of the error tell you that? Why did you think the problem was with getting the size? – Barmar Apr 06 '20 at 22:27

2 Answers2

3

mypath is a file and not a folder. With the command os.chdir(mypath) you are trying to change the folder - into an image.

It is generally very important, in which exact line an exception occurs. In this case it will be line 4.

To solve your problem: You can probably just delete this line.

Lydia van Dyke
  • 2,079
  • 3
  • 9
  • 21
2

It is failing because of the line os.chdir(mypath). You don't need to chdir().

Assuming the path is correct and the file exists, it should work (print the file size) if you remove the os.chdir() statement.

Rusty Widebottom
  • 919
  • 2
  • 3
  • 12