Get python tarfile to skip files without read permission
I'm trying to write a function that backs up a directory with files of different permission to an archive on Windows XP. I'm using the tarfile module to tar the directory. Currently as soon as the program encounters a file that does not have read permissions, it stops giving the error: IOError: [Errno 13] Permission denied: 'path to file'. I would like it to instead just skip over the files it cannot read rather than end the tar opera开发者_JAVA百科tion. This is the code I am using now:
def compressTar():
"""Build and gzip the tar archive."""
folder = 'C:\\Documents and Settings'
tar = tarfile.open ("C:\\WINDOWS\\Program\\archive.tar.gz", "w:gz")
try:
print "Attempting to build a backup archive"
tar.add(folder)
except:
print "Permission denied attempting to create a backup archive"
print "Building a limited archive conatining files with read permissions."
for root, dirs, files in os.walk(folder):
for f in files:
tar.add(os.path.join(root, f))
for d in dirs:
tar.add(os.path.join(root, d))
You should add more try statements :
for root, dirs, files in os.walk(folder):
for f in files:
try:
tar.add(os.path.join(root, f))
except IOError:
pass
for d in dirs:
try:
tar.add(os.path.join(root, d), recursive=False)
except IOError:
pass
[edit] As Tarfile.add is recursive by default, I've added the recursive=False
parameter when adding directories, otherwise you could run into problems.
You will need the same try
/except
blocks for when you are trying to add the files with read permissions. Right now, if any of the files or sub directories are not readable, then your program will crash.
Another option that isn't so reliant on try
blocks is to check the permissions before trying to add the file/folder to your tarball. There is a whole question about how to best do this (and some pitfalls to avoid when using Windows): Python - Test directory permissions
The basic pseudo code would be something like:
if folder has read permissions:
add folder to tarball
else:
for each item in folder:
if item has read permission:
add item to tarball
Just to add to what everyone else has said, there's a native python function to which you can pass the file parameter and the property you're looking for to check for that property: hasattr('/path/to/file.txt', "read")
OR hasattr('/path/to/file.txt', "write")
and so on
hope this helps anyone else out there
精彩评论