Put functions


I am learning Python. I have a readwrite function (file name, list) . filename is of type string. list - a list containing the lines that should be written in the file.

I have a simple function call as follows:

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

I ran into a problem that when I print the value of the file name argument inside the function definition, I get hello.txt and not xxHello.txt - the weird thing I did not expect when I do the same from commadline, for a sample function It works great. I wonder what I miss there.

Here is 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 , not xxHello.txt
This is my confusion, why he behaves strictly or I'm doing something wrong.

+6
source share
1 answer

Python is case sensitive . The two lines below relate to two different variables (note the capital β€œN” in the first):

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

What happens is that the second line selects the global variable filename instead of the argument to the filename function.

+12
source

Source: https://habr.com/ru/post/898960/


All Articles