2011-10-10 177 views
6


我正在學習Python。我有一個函數readwrite(文件名,列表)。文件名是字符串類型。列表是一個包含文件中wtitten字符串的列表。Python函數混淆

我有一個簡單的函數調用是這樣的:

fname = 'hello.txt' 
readwrite('xx'+fname, datalist) 

我面臨的問題,當我打印的功能定義中的文件名參數值,我得到hello.txt的,而不是xxHello.txt - 一個奇怪的事情,我沒有預料
當我從commadline做同樣的示例功能,它工作正常。 我不知道我在那裏失蹤。

下面就代碼:

def readwrite(fileName, list): 
    print 'arg file=',filename 
    curdir = os.getcwd(); 
    fullpath = os.path.join(curdir, filename); 
    print('full path calculated as: '+fullpath); 
    fileExist = os.path.exists(fullpath); 
    if(fileExist): 
     print 'file exists and opening in \'arw\'mode' 
     fiel = open(fileName, 'arw') # valid only if exists 
    else: 
     print "file doesnt exist; opening in \'w\'mode" 
     fiel = open(fileName, 'w')  # if it doesnt exist, we cant open it for reading as nothing to read. 

    for line in list: 
     fiel.write('\n'+line) 

    print 'position of new pointer = ', fiel.tell() 

- 主代碼調用函數:

filename = 'put.txt' 
strList = ['hello', 'how', 'are', 'you'] 
readwrite(('xx'+filename), strList); 

- 第二線在FN DEF 打印 'ARG文件=',文件名打印hello.txt而不是xxHello.txt
這是我的困惑,爲什麼它表現得很壞或者我做錯了什麼。

+2

不要使用'list'作爲變量名稱。通過這樣做,您將覆蓋對內置類「list」的引用。 – rplnt

+0

@aix已經回答了大小寫敏感問題,我想補充一點,「list」是一個內置函數,通常不是一個好主意,可以用它作爲參數或變量的名稱。 – fortran

+0

感謝您的反饋大gyz – Abhinav

回答

12

Python區分大小寫。下面兩行指的是兩個不同的變量(注意是大寫的「N」中的第一個):

def readwrite(fileName, list): 
    print 'arg file=',filename 

發生了什麼事是第二線拿起叫filename,而不是函數參數的全局變量稱爲fileName

+1

+1非常感謝。不能做+1,因爲我沒有15聲望 感覺我的錯誤愚蠢。 – Abhinav

+3

@abhinav:但是您可以通過點擊左側的複選標記來接受答案。即時+2代表你也是。另外,這不是一個愚蠢的錯誤,你寫了一個很好的問題。太糟糕了,我不能不止一次地讚揚它。這裏沒有很多新人知道如何寫出一個好問題。所以別擔心,你很快就會有足夠的聲望。 –

+1

歡迎來到社區!另外,順便說一下,在Python的末尾,所有這些分號都是不必要的,並且將它們排除在外是標準的。他們很醜陋:)'fiel'似乎也很尷尬;典型的名字是'f'和'a_file'。 –