Im trying to create a zipfile with the content of a folder ( some dirs and files ) using the code belllow:
import zip,os
path = "c:\\tester\\folderToZip"
zip = zipfile.ZipFile("zippedFolder.zip", "w")
for root, dirs, files in os.walk(path):
for file in files:
zip.write(os.path.join(root, file))
zip.close()
But after the code runs, when i check the zip file, the zip file, instead having the content of the folder "folderToZip" ( ex: f1,f2,f2, a.txt,b.txt,c.txt ) it have the full path of the variable path.
So, the question is, how can i create a zipfile based on a folder content, but not his fullpath ?
write takes a second optional parameter arcname, which when specified will provide the name for the file stored. Use that to specify the name you want.
If you only want the filename:
import zip,os
path = "c:\\tester\\folderToZip"
zip = zipfile.ZipFile("zippedFolder.zip", "w")
for root, dirs, files in os.walk(path):
for file in files:
filename = os.path.join(root, file)
zip.write(filename, filename)
zip.close()
Related
I am trying to zip all the files from a folder and places it in the same folder. Below is my code:
import os as __os
import zipfile
def zipdir(path, ziph):
for root, dirs, files in __os.walk(path):
for file in files:
print(file)
ziph.write(__os.path.join(root, file))
if __name__ == '__main__':
zip_name = 'test.zip'
working_directory = "C:\\Users\\Admin\\Downloads\\gaz"
archive_name = __os.path.join(working_directory, zip_name)
with zipfile.ZipFile(archive_name, 'w', zipfile.ZIP_DEFLATED) as zipf:
zipdir(working_directory + '', zipf)
I am trying to create zip of all the files inside a folder. I am expecting the code to create a zip in the same folder. Its going into infinite.
I don't really see an endless loop but you're including the newly created test.zip (empty) to the archive of the same name.
It would be better to check file before adding it to the archive:
def zipdir(path, ziph):
for root, dirs, files in __os.walk(path):
for file in files:
if file != zip_name:
print(file)
ziph.write(__os.path.join(root, file))
The zipdir() funciton is calling itself recursively, resulting in the infinite loop. Try zipf.write(). That function adds a file to a zip archive.
with zipfile.ZipFile(archive_name, 'w', zipfile.ZIP_DEFLATED) as zipf:
for root, dirs, files in __os.walk(working_directory):
for file in files:
if os.path.samefile(archive_path, os.path.join(root, file)):
continue
zipf.write(__os.path.join(root, file))
Edit: Check if archive_name file is located in working_directory
I am trying to identify all .kml in a specific directory and save them into a new directory. Is this possible? I'm able to print the file path but I would like to use Python to copy those files to a new directory.
Here is my code so far:
import os
# traverse whole directory
for root, dirs, files in os.walk(r'C:\Users\file_path_here'):
# select file name
for file in files:
# check the extension of files
if file.endswith('.kml'):
# print whole path of files
print(os.path.join(root, file))
Try this:
import os
# traverse whole directory
for root, dirs, files in os.walk(r'C:\Users\file_path_here'):
# select file name
for each_file in files:
# check the extension of files
if each_file.endswith('.kml'):
# print whole path of files
print(os.path.join(root, file))
kml_file = open(each_file, "r")
content = kml_file.read()
file.close()
with open('newfile.kml', 'w') as f:
f.write(content)
I have a directory structure that is like /level1/level2/level3/level4/level5 and in level5 I have .json files I want to replace with zipped up versions so from
/level1/level2/level3/level4/level5/{file1.json, file2.json, file3.json} to
/level1/level2/level3/level4/level5/{file1.zip, file2.zip, file3.zip}
However my code generates the zip files in the folder where the script is, which is level 3, resulting in /level1/level2/[level3]{file1.zip, file2.zip, file3.zip}/level4/level5/{file1.json, file2.json, file3.json}
In addition if I unzip the file I get the entire directory structure instead of just the file. For example if I unzip file1.zip I get /level1/level2/[level3]{(/level1/level2/level3/level4/level5/file1.json), file2.zip, file3.zip}/level4/level5/{file1.json, file2.json, file3.json}
I've tried different arguments but I'm not sure how to get the result I want. How can I accomplish this?
This is my code currently
path = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
level4, level5)
for root, dirs, files in os.walk(path, topdown=True):
print('This is root: ', root)
for file in files:
zf = zipfile.ZipFile(
'{}.zip'.format(file[:-5]), 'w',
zipfile.ZIP_DEFLATED)
zf.write(os.path.join(root, file))
zf.close()
You should create the zip file with the root path joined so that the zip file will be created where the JSON file is, and when writing the JSON file into the zip file, use the writestr method instead of write so that you can name the file with the path name you want, which in this case is just the file name with no path name at all:
for root, dirs, files in os.walk(path, topdown=True):
print('This is root: ', root)
for file in files:
zf = zipfile.ZipFile(os.path.join(root, '{}.zip'.format(file[:-5])), 'w', zipfile.ZIP_DEFLATED)
zf.writestr(file, open(os.path.join(root, file)).read())
zf.close()
I am trying the script below to rename all files in a folder.It is working fine,But when i am trying to run it outside the folder.It shows error.
import os
path=os.getcwd()
path=os.path.join(path,'it')
filenames = os.listdir(path)
i=0
for filename in filenames:
os.rename(filename, "%d.jpg"%i)
i=i+1
'it' is the name of the folder in which files lie.
Error:FileNotFoundError: [Errno 2] No such file or directory: '0.jpg' -> '0.jpg'
Print is showing names of files
When you do os.listdir(path) you get the filenames of files in the folder, but not the complete paths to those files. When you call os.rename you need the path to the file rather than just the filename.
You can join the filename to its parent folder's path using os.path.join.
E.g. os.path.join(path, file).
Something like this might work:
for filename in filenames:
old = os.path.join(path, filename)
new = os.path.join(path, "%d.jpg"%i)
os.rename(old, new)
i=i+1
You need to mention complete or relative path to file.
In this case, it should be
path + '/' + filename
or more generally,
newpath = os.path.join(path, filename)
I'm trying to make a script that copies all the files other than the zipped files from a source folder to another destination folder and extract zipped files from the source folder to the destination, this is what i have come till this far:
import os
import zipfile
import shutil
myPath = "Source dir"
for root, dirs, files in os.walk(myPath):
for file in files:
if file.endswith('.zip'):
fh = open(file, 'rb')
z = zipfile.ZipFile(fh)
for name in z.namelist():
outpath = "destination dir"#Put the name of the destination folder
z.extract(name, outpath)
fh.close()
else:
fileList = os.listdir('source dir')
for f in fileList:
shutil.copy2(f, 'destination directory')
The code shows no error but there is no output too.
From Python Standard Library To get a full path (which begins with top) to a file or directory in dirpath, do os.path.join(dirpath, name) so you should write
fh = open(so.path.join(root,file))
to have the correct path.