开发者

Python Functions Confusion

I am learning Python. I have a function readwrite(filename, list). filename is of type string. list is a list containing strings to be wtitten in the file.

I have a simple function call like this:

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

I am facing probl开发者_运维技巧em that when i print the filename argument value inside the function definition, i get hello.txt rather than xxHello.txt - a strange thing which i didnt expect

when i do same from commadline, for a sample function, it works fine. I wonder what I am missing over there.

Here s the code:

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() 

-- main code calling the function:

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

-- second line in fn def print 'arg file=',filename prints hello.txt rather than xxHello.txt

This is my confusion as why is it behaving starngely or am i doing smthing wrong.


Python is case-sensitive. The two lines below are referring to two different variables (note the capital "N" in the first one):

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

What's happening is that the second line picks up the global variable called filename instead of the function argument called fileName.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜