Reputation: 121
This question is about getting size of multiple files located inside the hard disk. The code has been improved based on the answers here:
import os, glob
with open ('file_size.txt', 'w') as outfile:
files= glob.glob ('*.jpg')
for file in files:
get_sizes = os.path.getsize (file)
for item in get_sizes:
if item < 1000:
size = str (item) + 'K'
else:
size = str (round ((item/(1024*1024)),1)) + 'M'
file_name = os.path.basename (file)
outfile.write(file_name + ' ' + size + '\n')
However the above code still produces the following error:
Traceback (most recent call last):
File "G:\test\test.py", line 6, in <module>
for item in get_sizes:
TypeError: 'int' object is not iterable
What's wrong?
Upvotes: 3
Views: 7542
Reputation: 1302
Looks like you're struggling with nesting if statements. Everything after the first if
will not execute unless the item's small enough, and if you get that far, nothing after the second if
will execute.
I'm assuming you'd like to set size
to something different based on how big the file is and then ALWAYS output a line to your output file. Unindenting will do that. I've also changed your second if
to an else
so that one or the other always executes.
Also, os.path.getsize() only returns the size for one file, so you don't need to loop over the result.
import os, glob
with open ("file_size.txt", "w") as outfile:
files= glob.glob ("G:\\*.jpg")
for file in files:
get_size = os.path.getsize (file)
if get_size < 1000:
size = str (item) + 'K'
else:
size = str (round ((item/(1024*1024)),1)) + 'M'
out_name = os.path.basename (file)
outfile.write(out_file + " " + size + "\n")
This takes the assignment to out_name
and the write to outfile
outside your if
statements so that they always execute, rather than being dependent on the if
conditions.
Upvotes: 5
Reputation: 114098
if item < 1000:
size = str (item) + 'K'
if item > 1000:
#this will never execute
#since you have already asserted that item < 1000
Upvotes: 1