mr.Arrow
mr.Arrow

Reputation: 51

can't get a file size in python

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

Upvotes: 0

Views: 859

Answers (2)

Lydia van Dyke
Lydia van Dyke

Reputation: 2516

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.

Upvotes: 3

Rusty Widebottom
Rusty Widebottom

Reputation: 984

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.

Upvotes: 2

Related Questions