2012-02-05 22 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) 

只是看起來更漂亮。

相關問題