[英]Python Functions Confusion
我正在學習Python。 我有一個函數readwrite(filename,list) 。 filename的類型為string。 list是一個包含要在文件中重寫的字符串的列表。
我有一個簡單的函數調用,如下所示:
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 print'arg file ='中的第二行,filename打印hello.txt而不是xxHello.txt
這是我的困惑,為什么它表現得很好,或者我做錯了什么。
Python區分大小寫 。 下面的兩行是指兩個不同的變量(注意第一個中的大寫“N”):
def readwrite(fileName, list):
print 'arg file=',filename
發生的事情是第二行選擇名為filename
的全局變量而不是名為fileName
的函數參數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.