I'm trying to understand how functions work and have a basic question. I'm trying to figure out how to set a variable into the function and don't know how. Probably easier for me to show my code:
I have a bit of code that unzips a file
fh = open(fn, 'rb')
z = zipfile.ZipFile(fh)
for name in z.namelist():
z.extract(name, outpath)
fh.close()
I can put this into a function by defining it as:
def extract_zip():
fh = open(fn, 'rb')
z = zipfile.ZipFile(fh)
for name in z.namelist():
z.extract(name, outpath)
fh.close()
And then I can call it by typing:
extract_zip()
But the purpose of putting this into a function is so I can use it over and over again. But when I use it a 2nd or 3rd time, the variable name won't be 'fn' but rather another variable name defined later.
How can i write this function but define 'fn' as a variable and then call it later by typing
extract_zip(2nd_filename)
Thanks
This is as simple as puting fn
as argument of your function
def extract_zip(fn):
fh = open(fn, 'rb')
z = zipfile.ZipFile(fh)
for name in z.namelist():
z.extract(name, outpath)
fh.close()
Sometime, you may also want to use a default name
def extract_zip(fn="default_name.extension"):
#...
Furthermore, note that your file name can be a full file name, which means that it can include the path to the file you want to read. For example, if your project layout is
your_working_direcory/
your_script.py
folder1/
folder2/
file_to_read.extension
you would have to define the full name of the file you want to read as
yourFullFileName = os.path.join(
os.path.dirname(__file__),# __file__ is the full name of your working script,
'folder1',
'folder2',
'file_to_read.extension'
)
which ensures the portability of your script (you don't have to worry about the operating-system dependant separator, mainly). Then you would use your function like so
extract_zip(fn=yourFullFileName)
def extract_zip(name_of_file):
fh = open(name_of_file, 'rb')
z = zipfile.ZipFile(fh)
for name in z.namelist():
z.extract(name, outpath)
fh.close()
The above allows you to set the name of the file as name_of_file='my filename'
To be able to reuse functions, you have to make the variable elements arguments to the function, eg:
def extract_zip(filename, outpath):
with zipfile.ZipFile(filename) as z:
z.extractall(outpath)
return z.namelist()
The return
returns alls the names of the archive objects, so that you can keep track of the items extracted.
files = {}
files[(filename, outpath)] = extract_zip('my.zip', 'output')
One Way You Can Change The Variable Is Add A input() Function (raw.input() for older Python versions)
var = input(What Is THe Filename? (Make It Exact!): )
var is whatever your variable is.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.