Python函数混乱

Abh*_*nav 6 python


我正在学习Python.我有一个函数readwrite(filename,list).filename的类型为string.list是一个包含要在文件中重写的字符串的列表.

我有一个简单的函数调用,如下所示:

fname = 'hello.txt'
readwrite('xx'+fname, datalist)
Run Code Online (Sandbox Code Playgroud)

我面临的问题是,当我在函数定义中打印文件名参数值时,我得到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() 
Run Code Online (Sandbox Code Playgroud)

- 调用函数的主代码:

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

- fn def print'arg file ='中的第二行,文件名打印hello.txt而不是xxHello.txt
这是我的困惑,为什么它表现得很好或者我做错了.

NPE*_*NPE 12

Python区分大小写.下面的两行是指两个不同的变量(注意第一个中的大写"N"):

def readwrite(fileName, list):
    print 'arg file=',filename
Run Code Online (Sandbox Code Playgroud)

发生的事情是第二行选择调用的全局变量filename而不是调用的函数参数fileName.

  • @abhinav:但你可以点击左侧的复选标记来接受答案.即时+2代表你也是.而且,这不是一个愚蠢的错误,你写了一个非常好的问题.太糟糕了,我不能不止一次地投票.这里没有多少新人知道如何写一个好问题.所以不要担心,你很快就会有足够的声誉. (3认同)