Reputation: 816
When I first coded this in to a single function, it worked. But I want to do more things when I am checking for files in to the directory, so I have divided the code in two functions : One checks for files on a directory that end with *.rar extension, if it finds a file that matches, it uncompresses it to a directory.
import shutil, os, patoolib, fnmatch, glob
def unrar():
patoolib.extract_archive(file, outdir="/root/tree/def")
def chktree():
for file in glob.glob('/root/tree/down/*'):
if fnmatch.fnmatch(file, '*.rar'):
unrar()
chktree()
Executing unrar()
after the if
from the function chktree():
does not work. I would like to know what I am doing wrong, this is the output :
Traceback (most recent call last):
File "autotube.py", line 16, in <module>
chktree()
File "autotube.py", line 14, in chktree
unrar()
File "autotube.py", line 6, in unrar
patoolib.extract_archive(file, outdir="/root/tree/def")
File "/usr/local/lib/python2.7/dist-packages/patoolib/__init__.py", line 676, in extract_archive
util.check_existing_filename(archive)
File "/usr/local/lib/python2.7/dist-packages/patoolib/util.py", line 389, in check_existing_filename
if not os.path.exists(filename):
File "/usr/lib/python2.7/genericpath.py", line 26, in exists
os.stat(path)
TypeError: coercing to Unicode: need string or buffer, type found
Upvotes: 1
Views: 154
Reputation: 75565
You need to pass the variable file
explicitly to the function you are calling. Also, file
is a special name in Python, so you should probably use a different name, such as my_file
or simply f
.
import shutil, os, patoolib, fnmatch, glob
def unrar(my_file):
patoolib.extract_archive(my_file, outdir="/root/tree/def")
def chktree():
for f in glob.glob('/root/tree/down/*'):
if fnmatch.fnmatch(f, '*.rar'):
unrar(f)
chktree()
Additionally, as @mgilson noted, the reason for the actual error you are seeing is that Python thinks you are referring to the built-in name file
since you did not pass a parameter which shadowed it. Had you used a different name, you would have gotten a NameError
instead.
Upvotes: 3
Reputation: 78690
In python 2, there is a file
builtin, which is what you are calling extract_archive
with in your unrar
function. You are not using your loop variable from chktree
because it only lives within chktree
. You can write it like this:
def unrar(f):
patoolib.extract_archive(f, outdir="/root/tree/def")
def chktree():
for f in glob.glob('/root/tree/down/*'):
if fnmatch.fnmatch(f, '*.rar'):
unrar(f)
I used f
as the name for the file to prevent masking the builtin.
Upvotes: 3