[Tutor] How to invoke different member-function according to different object?
daedae11
daedae11 at 126.com
Sat Jan 7 04:57:06 CET 2012
I was asked to write a program to move files between ZIP(.zip) and TAR/GZIP(.tgz/.tar.gz) or TAR/BZIP2(.tbz/.tar.bz2) archive.
my code is:
import zipfile;
import tarfile;
import os;
from os import path ;
def showAllFiles(fileObj):
if fileObj.filename.endswith("zip"):
if isinstance(fileObj, zipfile.ZipFile):
print "j"*20;
for name in fileObj.namelist():
print name;
else:
for name in fileObj.getnames():
print name;
def moveFile(srcObj, dstObj):
fileName = raw_input("input the name of the file to move: ");
srcObj.extract(fileName);
if isinstance(dstObj, zipfile.ZipFile):
dstObj.write(fileName);
else:
dstObj.addfile(tarfile.TarInfo(fileName));
os.remove(fileName);
def main():
intro = """
enter a choice
(M)ove file from source file to destinatiom file
(S)how all the files in source file
(Q)uit
your choice is: """
srcFile = raw_input("input the source file name: ");
dstFile = raw_input("input the destination file name: ");
while True:
with ( zipfile.ZipFile(srcFile, "r") if srcFile.endswith("zip") else tarfile.open(srcFile, "r"+":"+path.splitext(srcFile)[1][1:]) ) as srcObj, \
( zipfile.ZipFile(dstFile, "r") if
dstFile.endswith("zip") else
tarfile.open(dstFile, "w"+":"+path.splitext(dstFile)[1][1:]) ) as dstObj:
choice = raw_input(intro)[0].lower();
if choice == "s":
showAllFiles(srcObj);
elif choice == "m":
moveFile(srcObj, dstObj);
elif choice == "q":
break;
else:
print "invalid command!"
if __name__ == '__main__':
main();
But there are some problems.
1. It could extract file successfully, but can't add files to .tar.gz file.
2. I think it's a little tedious, but I don't know how to improve it.
Please give me some help , thank you!
daedae11
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120107/bf48c27f/attachment.html>
More information about the Tutor
mailing list