加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python函数混乱

发布时间:2020-12-16 23:38:21 所属栏目:Python 来源:网络整理
导读:我正在学习 Python.我有一个函数readwrite(filename,list). filename的类型为string. list是一个包含要在文件中重写的字符串的列表. 我有一个简单的函数调用,如下所示: fname = 'hello.txt'readwrite('xx'+fname,datalist) 我面临的问题是,当我在函数定义中
我正在学习 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,filename

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读