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 problem 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.
There are three functions in python that provide vast practicality and usefulness when programming. These three functions, which provide a functional programming style within the object-oriented python language, are the map(), filter(), and reduce() functions.
The terms parameter and argument can be used for the same thing: information that are passed into a function. From a function's perspective: A parameter is the variable listed inside the parentheses in the function definition. An argument is the value that are sent to the function when it is called.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With