Trying_hard
Trying_hard

Reputation: 9501

python zipfile basename

I have some homework that I am trying to complete. I don't want the answer. I'm just having trouble in starting. The work I have tried is not working at all... Can someone please just provide a push in the right direction. I am trying to learn but after trying and trying I need some help.

I know I can you os.path.basename() to get the basename and then add it to the file name but I can't get it together.

Here is the assignment

In this project, write a function that takes a directory path and creates an archive of the directory only. For example, if the same path were used as in the example ("c:\\xxxx\\Archives\\archive_me"), the zipfile would contain archive_me\\groucho, archive_me\\harpo and archive_me\\chico.

The base directory (archive_me in the example above) is the final element of the input, and all paths recorded in the zipfile should start with the base directory.

If the directory contains sub-directories, the sub-directory names and any files in the sub-directories should not be included. (Hint: You can use isfile() to determine if a filename represents a regular file and not a directory.)

Thanks again any direction would be great.

Upvotes: 4

Views: 837

Answers (1)

BoppreH
BoppreH

Reputation: 10173

It would help to know what you tried yourself, so I'm only giving a few pointers to methods in the standard libraries:

  • os.listdir to get the a list of files and folders under a given directory (beware, it returns only the file/folder name, not the full path!)

  • os.path.isfile as mentioned in the assignment to check if a given path represents a file or a folder

  • os.path.isdir, the opposite of os.path.isfile (thanks inspectorG4adget)

  • os.path.join to join a filename with the basedir without having to worry about slashes and delimiters

  • ZipFile for handling, well, zip files

  • zipFile.write to write the files found to the zip

I'm not sure you'll need all of those, but it doesn't hurt knowing they exist.

Upvotes: 5

Related Questions