How To Pass A Tuple To A Python Function
I've been trying to pass a tuple to a function that I created earlier, however, I m still not able to make it work. My objective is to pass a tuple containing a list of path+file f
Solution 1:
You're successfully passing the tuple to your own function. But os.path.getsize()
doesn't accept tuples, it only accepts individual strings.
Also, this question is a bit confusing because your example isn't a path + file tuple, which would be something like ('C:\\', 'vd36e404.vdb')
.
To handle something like that, you could do this:
import os
def fileF(EXl):
filesize= os.path.getsize(EXl[0] + EXl[1])
print (filesize);
If you want to print values for multiple paths, do as Bing Hsu says, and use a for loop. Or use a list comprehension:
def fileF(EXl):
filesizes = [os.path.getsize(x) for x in EXl]
print filesizes
Or if you want to, say, return another tuple:
deffileF(EXl):
returntuple(os.path.getsize(x) for x in EXl)
Solution 2:
import osfor xxx in EXl:
filesize= os.path.getsize(xxx)
print (filesize);
Solution 3:
A way more elegant example:
map(fileF, EX1)
This will actually call fileF separately with each of the elements in EX1. And of course, this is equivalent to
for element in EX1:
fileF(element)
Just looks prettier.
Post a Comment for "How To Pass A Tuple To A Python Function"