I have a lot of sub folders containing zip files. I want find all zips, extract where they are and delete after extraction. So far I've managed to write this:
import zipfile,fnmatch,os
rootPath = r"."
pattern = '*.zip'
for root, dirs, files in os.walk(rootPath):
for filename in fnmatch.filter(files, pattern):
print(os.path.join(root, filename))
zipfile.ZipFile(os.path.join(root, filename)).extractall(os.path.join(root, os.path.splitext(filename)[0]))
I find and extract all the zips but no matter how I try to delete a zip I get an access denied error. Is this a proper way of implementing what I'm after? How can I delete archives after extraction?
Thx
Related
I'm trying to create a zip file from several files. For example, I have 3 files
file1
file2
file3
I want to create a zip folder that contains all these files
Is there some way to create zip folder containing multiple files in Spark(Python)?
First of all spark is a framework which is also in python language. I did not understand how do you relate zip files and spark in this question.
If you want to create zip files in python, check out zipfiles library. Try and if you're stuck copy your code here. Then we will try to help.
from zipfile import ZipFile
# create a ZipFile object
with ZipFile('sampleDir.zip', 'w') as zipObj:
# Iterate over all the files in directory
for folderName, subfolders, filenames in os.walk(dirName):
for filename in filenames:
#create complete filepath of file in directory
filePath = os.path.join(folderName, filename)
# Add file to zip
zipObj.write(filePath)
o/p:
sampleDir/file1.csv 2018-11-30 21:44:46 2829
sampleDir/file2.csv 2018-11-30 21:44:36 3386
sampleDir/file3.csv 2018-11-30 21:44:56 3552
I`m creating a program that can read certain data from some txt files, the problem comes when I try to use the files inside subdirectories (the subdirectories are inside the main directory of the program. I'm using a for the option to find all the files and then create a new file with the info that I found. The main problem is that I can't read those files.
I tried using a for a function that creates a list of directories, files and roots, this works fine, but in the moment of running the file it says "it cannot be found txt file". The if not condition is made so the program excludes all.DS_Store files. I think the problem could be the way I open the file but im not sure
for root, directories, filenames in os.walk("Files_to_Insert"):
if not (filenames[-1] == ".DS_Store"):
lastFile = filenames[-1]
print lastFile
with open (lastFile, 'rt') as myfile:
IOError: [Errno 2] No such file or directory: txt
The mistake happens in the with open because it can`t find the file.
When I print I get all the txt files, but I can,t use them in the "with open"
A typical os.walk I use goes like this:
import os
for root, directories, filenames in os.walk("."):
for f in filenames:
if f.endswith(".DS_Store"):
continue
print(os.path.abspath(f))
with open (os.path.abspath(f), 'rt') as myfile:
I solve it by giving the path and the text file in separate strings:
for root, directories, filenames in os.walk("Files_to_Insert"):
if not(filenames[-1] == ".DS_Store"):
lastFile = filenames[-1]
# print (lastFile)
with open(str(root) + '/' + lastFile,'rt') as myfile:
As per the code below I am having issues with the zipping a directory using the python 3 shutil.make_archive function. The .testdir will be zipped but it is being zipped in /home/pi, instead of /home/pi/Backups.
zip_loc = '/home/pi/.testdir'
zip_dest = '/home/pi/Backups/'
shutil.make_archive(zip_loc, 'zip', zip_dest)
Could anyone explain what I am doing wrong?
Reading the docs here I came up with:
zip_loc = '/home/pi/.testdir'
zip_dest = '/home/pi/Backups/'
shutil.make_archive(base_dir=zip_loc, root_dir=zip_loc, format='zip', base_name=zip_dest)
From the docs:
base_name is the name of the file to create, including the path, minus any format-specific extension.
root_dir is a directory that will be the root directory of the archive; for example, we typically chdir into root_dir before creating the archive.
base_dir is the directory where we start archiving from; i.e. base_dir will be the common prefix of all files and directories in the archive.
root_dir and base_dir both default to the current directory.
Before to write the archive, move to the good directory :
old_path = os.getcwd()
os.chdir(path)
-> write the archive
After writing the archive move back to old directory :
os.chdir(old_path)
you know special files or folders where the first place is a point. For example: .example_folder or .examaple_file. Think about the .htaccess/.htpassword files. I know how to delete folders and files on the regular way with Python. But how can I delete some special files like this? The other problem is the special files don't have extensions like .txt oder .jpg etc.. When I try to delete the special files/folders on the regular way Python skips all the special files/folder. Does someone has any idea?
def delete_temp_update_files(path_files):
files = glob.glob(path_files)
for f in files:
os.remove(f)
def delete_temp_update_folders(folder_path, path_files):
folder_paths = glob.glob(folder_path)
'''
First, all folders are deleted in this current folder (folder_paths).
'''
if not folder_paths:
'''
The list (folder_paths) is empty, that means there aren't somer folders.
In this case its enough to delete all files - everything including
hidden files.
'''
result_files = delete_temp_update_files(path_files)
return result_files
else:
'''
There are some folders. Before the files are deleted, the folder must be deleted.
'''
for folder_element in folder_paths:
shutil.rmtree(folder_element, ignore_errors=True)
'''
Now all folders are delete have been deleted. Netx all files should be deleted.
'''
result_files = delete_temp_update_files(path_files)
return result_files
def on_delete_files_folders(update_temp_zip_file):
# The variable named (all_files) shows all files - everything including hidden files
all_files = os.path.join(update_temp_zip_file, '*')
# The variable named (all_folders) shows all folders in current folder.
all_folders = os.path.join(update_temp_zip_file, '*/')
delete_temp_update_folders(all_folders, all_files)
on_delete_files_folders("PATH/TO/YOUR/FOLDER")
Your decision is rather sophisticated.
You may use my script below:
import os
def del_recursive(path):
for file in os.listdir(path):
file = os.path.join(path, file)
if os.path.isdir(file):
try:
os.rmdir(file)
except:
del_recursive(file)
os.rmdir(file)
else:
os.remove(file)
If you want to delete everything in a directory you also may use shutil.rmtree(). Both variants work on Python 2.7.3.
I am working on a search-and-destroy type program which I need it to do is search all directories with a certain file-name and append them to a list. after that delete all those files...not objects in list or the list...
import os
file_list=[]
for root, dirs, files in os.walk(path-to-dir'):
for f_name in files:
if f_name.startswith("file-name"):
file_list.append(f_name)
I could write up to appending part of the code but I don't know next...
Some help please
To remove a file from your computer, use os.remove(). It takes full path to the file as it's parameter, so instead of calling os.remove("infectedFile.dll") you would call os.remove("C:/program files/avira/infectedFile.dll")
So your file_list should contain full paths to the files, and then just call:
for file in file_list:
os.remove(file)
Modify your file_list.append(f_name). The f_name is only a bare name. You need to add the path to the file name in the time of processing, because you do not know where the file was found in the directory hierarchy:
file_list.append(os.path.join(root, f_name))
The root variable contains the path during walking.
To make check whether your code works, just print the content of the list:
print('\n'.join(file_list))
Or you can do it in the loop to get ready for the later part:
for fname in file_list:
print(fname)
Then you just add the os.remove(fname) to remove the file name:
for fname in file_list:
print('removing', fname)
os.remove(fname)