1

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 form which I want to discover the size and print it out.

Here's my code

EXl = ('C:\\vd36e404.vdb','C:\\vd368c03.vdb')

def fileF(EXl):
    import os
    filesize = os.path.getsize(EXl)
    print (filesize);

fileF(EXl)

These are the errors:

Traceback (most recent call last):
  File "C:\Documents and Settings\Administrator\workspace\test1py\testcallMyF.py", line 13, in <module>
    fileF(EXl)
  File "C:\Documents and Settings\Administrator\workspace\test1py\testcallMyF.py", line 9, in fileF
    filesize= os.path.getsize(EXl)
  File "C:\Python27\lib\genericpath.py", line 49, in getsize
    return os.stat(filename).st_size
TypeError: coercing to Unicode: need string or buffer, tuple found

Could anyone explain to me why?(I'm using Python 2.7.2)

0

3 Answers 3

4

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:

def fileF(EXl):
    return tuple(os.path.getsize(x) for x in EXl)
Sign up to request clarification or add additional context in comments.

Comments

3
import   os

for xxx in EXl:
    filesize= os.path.getsize(xxx)
    print (filesize);

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.