Unable to delete files of certain extension - python

I'm trying to delete some archives in a folder.
Here is what I've written to do that:
import sys
import os
from os import listdir
from os.path import join
dir_path = os.path.dirname(os.path.realpath(__file__))
for file in dir_path:
if (file.endswith(".gz")) or (file.endswith(".bz2")):
os.remove(join((dir_path), file))
print("Removed file.")
print("Done.")
When I run the module, it just prints "Done." but deletes no files, even though there are files with that extension in the same directory as the module.
Can't figure out what I'm doing wrong, help?

It looks like you missed os.listdir(dir_path) in the for-loop.

This seems to have worked:
import sys
import os
from os import listdir
from os.path import join
dirdir = "/Users/kosay.jabre/Desktop/Programming/Password List"
dir_path = os.listdir(dirdir)
for file in dir_path:
if (file.endswith(".gz")) or (file.endswith(".bz2")):
os.remove(file)
print("Done.")

Related

Recursively unzipping a folder with ZipFile/Python

I am trying to write a script which can unzip something like this:
Great grandfather.zip
Grandfather.zip
Father.zip
Child.txt
What I have so far:
from os import listdir
import os
from zipfile import ZipFile, is_zipfile
#Current Directory
mypath = '.'
def extractor(path):
for file in listdir(path):
if(is_zipfile(file)):
print(file)
with ZipFile(file,'r') as zipObj:
path = os.path.splitext(file)[0]
zipObj.extractall(path)
extractor(path)
extractor(mypath)
I can unzip great grandfather and when I call the extractor again with grandfather as path. It doesn't go inside the if statement. Even though, I can list the contents of grandfather.
Replace extractor(path) by these two lines:
os.chdir(path)
extractor('.')
So your code becomes:
from os import listdir
import os
from zipfile import ZipFile, is_zipfile
#Current Directory
mypath = '.'
def extractor(path):
for file in listdir(path):
if(is_zipfile(file)):
print(file)
with ZipFile(file,'r') as zipObj:
path = os.path.splitext(file)[0]
zipObj.extractall(path)
os.chdir(path)
extractor('.')
extractor(mypath)

Copy pdfs in a directory to folders with the same name as the PDFs

I want to put the pdfs I have in a directory in to the folders with the same name. Those folders with the same name have already been created and are in the same directory as the pdf files I want to move in to them.
I am relatively new at python and have not gotten very far on the code. Currently when I run the below it only prints the .pdf files but does not print the subfolders within the directory (that is besides the point but I am not sure why I cant see the sub folders in the directory in the below code.)
import os
from shutil import copyfile
path_to_files = "C:\\tmp\\all_files_converted\\"
def copy_documents(file_path):
for f in os.listdir(file_path):
print(f)
copy_documents(path_to_files)
folders in directory C://tmp//all_files_converted//
pdf files with the same name as the folders in the same directory C://tmp//all_files_converted//
You can use pathlib and shutil to perform this:
from pathlib import Path
from shutil import move
path_to_files = Path(r"C:\tmp\all_files_converted")
for pdf_path in path_to_files.glob("*.pdf"):
dir_path = path_to_files / pdf_path.stem
dir_path.mkdir()
move(pdf_path, dir_path / pdf_path.name)
You can use shutil.move(src, dst)
import shutil
shutil.move(src, dst)
import os
from shutil import copyfile
from glob import glob
path_to_files = "pasta"
def copy_documents(path_to_files):
# os.path is a module to work with file paths
# Using the module glob to list all pdf files of a folder
for file_path in glob(os.path.join(path_to_files, "*.pdf")):
# basename will return the filename without the rest of the path ie: "something.pdf"
pdf_file_name = os.path.basename(file_path)
dest_folder = os.path.join(path_to_files, pdf_file_name[:-4])
print(f"Copy {file_path} to {dest_folder}")
copyfile(file_path, os.path.join(dest_folder, pdf_file_name))
copy_documents(path_to_files)
I recommend reading https://docs.python.org/3/library/os.path.html and https://docs.python.org/3/library/glob.html
for more info.

Delete a specific folder with a path as a parameter in python

I want to delete a Folder named "testfolder" and all the subfolders and files in it. I want to give the "testfolder" path as a parameter when calling the python file. For example ...... (testfolder location) and there it should delete the "testfolder" when the folder exists
I guess this might be what you're looking for
import os
import shutil
pathLocation = # Whatever your path location is
if os.path.exists(pathLocation):
shutil.rmtree(pathLocation)
else:
print('the path doesn\'t exist')
You can use shutil.rmtree() for removing folders and argparse to get parameters.
import shutil
import argparse
import os
def remove_folder(folder_path='./testfolder/'):
if os.path.exists(folder_path):
shutil.rmtree(folder_path)
print(f'{folder_path} and its subfolders are removed succesfully.')
else:
print(f'There is no such folder like {folder_path}')
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Python Folder Remover')
parser.add_argument('--remove', '-r', metavar='path', required=True)
args = parser.parse_args()
if args.remove:
remove_folder(args.remove)
You can save above script as 'remove.py' and call it from command prompt like:
python remove.py --remove "testfolder"
Better to use absolute path and import only the rmtree function from shutil import rmtree as this is a large package the above line will only import the required function.
from shutil import rmtree
rmtree('directory-absolute-path')

How to select and copy files with specific file names from one directory to another?

I have a directory with two different types of filenames daily/monthly:
report_20-10-2019.csv
report_21-10-2019.csv
report_22-10-2019.csv
report_09-2019.csv
report_10-2019.csv
report_11-2019.csv
I'm trying to copy only daily files to another directory. So far I'm able to copy all the files with the below code:
import shutil
import os
import glob
source_daily = '/path/to/files/to/copy/*.csv'
dest1 = 'path/to/directory/where/i/paste/my/files/'
files = os.listdir(source)
for file in glob.glob(source):
shutil.copy(file, dest1);
Would someone be able to help with this? Thanks in advance!
You can certainly do that,
import shutil
import os
import re
source = '/path/to/files/to/copy/'
dest1 = 'path/to/directory/where/i/paste/my/files/'
for filename in os.listdir(source):
filepath = os.path.join(source, filename)
if os.path.isfile(filepath):
if re.search(r"[0-9]+-[0-9]+-[0-9]+\.csv", filepath):
shutil.copy(filepath, dest1)
Hope it addresses your problem!
Using Regular Expressions should work for you:
import re
import shutil
import os
import glob
source_daily = '/path/to/files/to/copy/*.csv'
dest1 = 'path/to/directory/where/i/paste/my/files/'
files = os.listdir(source)
pattern = re.compile('\w+_[0-3]\d-[0-1]\d-\d{4}.csv') #naming-pattern
for file in glob.glob(source):
if pattern.match(file):
shutil.copy(file, dest1);

Move child folder contents to parent folder in python

I have a specific problem in python. Below is my folder structure.
dstfolder/slave1/slave
I want the contents of 'slave' folder to be moved to 'slave1' (parent folder). Once moved,
'slave' folder should be deleted. shutil.move seems to be not helping.
Please let me know how to do it ?
Example using the os and shutil modules:
from os.path import join
from os import listdir, rmdir
from shutil import move
root = 'dstfolder/slave1'
for filename in listdir(join(root, 'slave')):
move(join(root, 'slave', filename), join(root, filename))
rmdir(join(root, 'slave'))
I needed something a little more generic, i.e. move all the files from all the [sub]+folders into the root folder.
For example start with:
root_folder
|----test1.txt
|----1
|----test2.txt
|----2
|----test3.txt
And end up with:
root_folder
|----test1.txt
|----test2.txt
|----test3.txt
A quick recursive function does the trick:
import os, shutil, sys
def move_to_root_folder(root_path, cur_path):
for filename in os.listdir(cur_path):
if os.path.isfile(os.path.join(cur_path, filename)):
shutil.move(os.path.join(cur_path, filename), os.path.join(root_path, filename))
elif os.path.isdir(os.path.join(cur_path, filename)):
move_to_root_folder(root_path, os.path.join(cur_path, filename))
else:
sys.exit("Should never reach here.")
# remove empty folders
if cur_path != root_path:
os.rmdir(cur_path)
You will usually call it with the same argument for root_path and cur_path, e.g. move_to_root_folder(os.getcwd(),os.getcwd()) if you want to try it in the python environment.
The problem might be with the path you specified in the shutil.move function
Try this code
import os
import shutil
for r,d,f in os.walk("slave1"):
for files in f:
filepath = os.path.join(os.getcwd(),"slave1","slave", files)
destpath = os.path.join(os.getcwd(),"slave1")
shutil.copy(filepath,destpath)
shutil.rmtree(os.path.join(os.getcwd(),"slave1","slave"))
Paste it into a .py file in the dstfolder. I.e. slave1 and this file should remain side by side. and then run it. worked for me
Use this if the files have same names, new file names will have folder names joined by '_'
import shutil
import os
source = 'path to folder'
def recursive_copy(path):
for f in sorted(os.listdir(os.path.join(os.getcwd(), path))):
file = os.path.join(path, f)
if os.path.isfile(file):
temp = os.path.split(path)
f_name = '_'.join(temp)
file_name = f_name + '_' + f
shutil.move(file, file_name)
else:
recursive_copy(file)
recursive_copy(source)
Maybe you could get into the dictionary slave, and then
exec system('mv .........')
It will work won't it?

Categories

Resources