Create zip file and ignore directory structure
You can use -j
.
-j
--junk-paths
Store just the name of a saved file (junk the path), and do not
store directory names. By default, zip will store the full path
(relative to the current directory).
How to zip folder without full path
By default, zip will store the full path relative to the current directory. So you have to cd
into public_html
before running zip
:
$output = 'cd /home/user/public_html; zip -rq my-zip.zip folder-one -x missthis/\*';
shell_exec($output);
Cannot zip directory from within R without including full file path
You can use the extras
parameter of the zip()
function.
So:
zip(zipfile = paste(path_out,unitList[ii],"_",Sys.Date(),sep=""), files = files2zip, extras = '-j')
zipping files in python without folder structure
From the documentation:
ZipFile.write(filename, arcname=None, compress_type=None,
compresslevel=None)Write the file named filename to the archive, giving it the archive
name arcname (by default, this will be the same as filename, but
without a drive letter and with leading path separators removed).
So, just specify an explicit arcname
:
with zp(os.path.join(self.savePath, self.selectedIndex + ".zip"), "w") as zip:
for file in filesToZip:
zip.write(self.folderPath + file, arcname=file)
How to create a zip file without entire directory structure
I don't believe zip has a way to exclude the top level directory. I think your best bet would be to do something like:
pushd /foo; zip -r out.zip ./bar; popd;
But this is exactly the sort of answer you said you didn't want.
Java: Add files to zip-file recursively but without full path
Whilst this can be done with the ancient ZipOutputStream
I would recommend against it.
It is much more intuitive to think about a Zip archive as a compressed filesystem inside a file, than a stream of bytes. For this reason, Java provides the ZipFileSystem
.
So all you need to do is open the Zip as a FileSystem
and then manually copy files across.
There are a couple of gotchas:
- You need to only copy files, directories need to be created.
- The NIO API does not support operations such as
relativize
across different filesystems (reasons should be obvious) so this you need to do yourself.
Here are a couple of simple methods that will do exactly that:
/**
* This creates a Zip file at the location specified by zip
* containing the full directory tree rooted at contents
*
* @param zip the zip file, this must not exist
* @param contents the root of the directory tree to copy
* @throws IOException, specific exceptions thrown for specific errors
*/
public static void createZip(final Path zip, final Path contents) throws IOException {
if (Files.exists(zip)) {
throw new FileAlreadyExistsException(zip.toString());
}
if (!Files.exists(contents)) {
throw new FileNotFoundException("The location to zip must exist");
}
final Map<String, String> env = new HashMap<>();
//creates a new Zip file rather than attempting to read an existing one
env.put("create", "true");
// locate file system by using the syntax
// defined in java.net.JarURLConnection
final URI uri = URI.create("jar:file:/" + zip.toString().replace("\\", "/"));
try (final FileSystem zipFileSystem = FileSystems.newFileSystem(uri, env);
final Stream<Path> files = Files.walk(contents)) {
final Path root = zipFileSystem.getPath("/");
files.forEach(file -> {
try {
copyToZip(root, contents, file);
} catch (IOException e) {
throw new RuntimeException(e);
}
});
}
}
/**
* Copy a specific file/folder to the zip archive
* If the file is a folder, create the folder. Otherwise copy the file
*
* @param root the root of the zip archive
* @param contents the root of the directory tree being copied, for relativization
* @param file the specific file/folder to copy
*/
private static void copyToZip(final Path root, final Path contents, final Path file) throws IOException {
final Path to = root.resolve(contents.relativize(file).toString());
if (Files.isDirectory(file)) {
Files.createDirectories(to);
} else {
Files.copy(file, to);
}
}
How to eliminate absolute path in zip archive if absolute paths for files are provided?
The zipfile write() method supports an extra argument (arcname) which is the archive name to be stored in the zip file, so you would only need to change your code with:
from os.path import basename
...
zip.write(first_path, basename(first_path))
zip.write(second_path, basename(second_path))
zip.close()
When you have some spare time reading the documentation for zipfile will be helpful.
zip file and avoid directory structure
The zipfile.write()
method takes an optional arcname
argument that specifies what the name of the file should be inside the zipfile
I think you need to do a modification for the destination, otherwise it will duplicate the directory. Use :arcname
to avoid it. try like this:
import os
import zipfile
def zip(src, dst):
zf = zipfile.ZipFile("%s.zip" % (dst), "w", zipfile.ZIP_DEFLATED)
abs_src = os.path.abspath(src)
for dirname, subdirs, files in os.walk(src):
for filename in files:
absname = os.path.abspath(os.path.join(dirname, filename))
arcname = absname[len(abs_src) + 1:]
print 'zipping %s as %s' % (os.path.join(dirname, filename),
arcname)
zf.write(absname, arcname)
zf.close()
zip("src", "dst")
Related Topics
How to Run Cronjobs More Often Than Once Per Minute
JSON_Encode Function: Special Characters
Mysqli Query Results to Show All Rows
PHP Read_Exif_Data and Adjust Orientation
.Htaccess Issues: No Input File Specified
How to Use Open Id as Login System
Single Quotes or Double Quotes for Variable Concatenation
Differencebetween Find(), Findorfail(), First(), Firstorfail(), Get(), List(), Toarray()
Not Equal to != and !== in PHP
Call a C Program from PHP and Read Program Output
Move_Uploaded_File() Function Is Not Working
Using Strtotime for Dates Before 1970
Custom Pagination View in Laravel 5
Shorthand for Arrays: Is There a Literal Syntax Like {} or []