2012-02-05 134 views
1

我一直在试图传递一个元组到我之前创建的函数,但是,我仍然无法使它工作。 我的目标是传递一个包含我想要发现大小并打印出来的路径+文件形式列表的元组。如何传递一个元组到一个python函数

这里是我的代码

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

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

fileF(EXl) 

这些都是错误的:

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 

能满足我为什么(我使用Python 2.7.2)谁能解释

回答

3
import os 

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

这就是我一直在寻找的! – nassio 2012-02-05 18:37:45

4

?你成功地将元组传递给你自己的函数。但os.path.getsize()不接受元组,它只接受单个字符串。

此外,这个问题有点令人困惑,因为你的例子不是一个路径+文件元组,这可能类似于('C:\\', 'vd36e404.vdb')。如果你要打印值的多条路径,请执行Bing Hsu说,并用一个for循环

import os 

def fileF(EXl): 
    filesize= os.path.getsize(EXl[0] + EXl[1]) 
    print (filesize); 

要处理这样的事情,你可以做到这一点。或者使用列表理解:

def fileF(EXl): 
    filesizes = [os.path.getsize(x) for x in EXl] 
    print filesizes 

或者,如果你想,说,返回另一个元组:

def fileF(EXl): 
    return tuple(os.path.getsize(x) for x in EXl) 
2

一种方法更优雅的例子:

map(fileF, EX1) 

这实际上将调用fileF与EX1中的每个元素分开。当然,这相当于

for element in EX1: 
    fileF(element) 

只是看起来更漂亮。

相关问题