i am pretty bad with using python but im trying to learn. So i have a script that extracts .zip and .rar files for me and that works flawlessly, now the only thing i want to implement is that if the script extracts a .zip or a .rar i want it to use Pushbullet to send a notification to my phone. This is being achieved with pushbullet.py
Anyway here is the script as of now:
import os
from subprocess import check_call
from os.path import join
from pushbullet import Pushbullet
from pyunpack import Archive
pb = Pushbullet("APIkey")
path = "/mnt/synology/Torrents/completed"
for root, dirs, files in os.walk(path):
if not any(f.endswith(".mkv") for f in files):
for file in files:
pth = join(root, file)
found_r = False
try:
if file.endswith(".zip"):
push = pb.push_note("NUC", "Extracting")
Archive(pth).extractall(root)
found_zip = True
elif not found_r and file.endswith((".rar")):
push = pb.push_note("NUC", "Extracting")
Archive(pth).extractall(root)
found_r = True
break
except:
pass
So right now it's pushing to my phone on every match it finds which is many matches and not what i want. I want it to push on just a successfull Extraction.
Does anyone know of a solution ?
Related
im creating script in python that get all files on disk, but no folders only files. Its my code.
import hashlib
import os
if os.name != "nt":
print("Sorry this script works only on Windows!")
path = "C://"
dir_list = os.listdir(path)
print(dir_list)
You can use for example the pathlib library and build something like that:
import pathlib
path = "" # add your path here don't forget a \ at the end on windows
for i in os.listdir(path):
if pathlib.Path(path + i).is_dir() is not True:
print(i)
It iterates through the current directory and checks if its a directory, by creating a Path object from the list entry and then checks on that object if it is a directory.
I am using python and I'm extremely new. I have a folder with hundreds of files, I have renamed their extensions as jp,gi,jpe and mp. So, I would like to loop through all of them, rename them all according to their extension. If it's jp then jpg, if it's jpe then jpeg, gif for gi and mp4 for mp. I know that it's a lot but, answer would be appreciated! Thanks!
You need to launch this file from directory, where all 'broken' files are located. You're welcome.
import os
from os import listdir
from os.path import isfile, join
# Get path to current dir
cwd = os.getcwd()
# Get all files in dir
onlyfiles = [f for f in listdir(cwd) if isfile(join(cwd, f))]
for file in onlyfiles:
# Get the current format
s = file.split(".")
br = s[-1]
if br == 'jp':
new = 'jpg'
elif br == 'gi':
new = 'gif'
elif br =='jpe':
new = 'jpeg'
else:
continue
# Change format and get new filename
s[-1] = new
s = '.'.join(s)
# Rename file
os.rename(file, s)
print(f"Renamed {file} to {s}")
jp then jpg, if it's jpe then jpeg, gif for gi and mp4 for mp
You can first create a dictionary like this:
extensions={'jp':'jpg','jpe':'jpeg','gi':'gif','mp':'mp4'}
Then import the os module, and use os.listdir(folder_path), followed by os.rename()
import os
folder_path='/.../.../folder'
extensions={'jp':'jpg','jpe':'jpeg','gi':'gif','mp':'mp4'}
for i in os.listdir(folder_path):
paths=i.split('.') #==== Split the string based on the parameter
if extensions.get(paths[-1])!=None: #=== If a key is not present, it returns None. So if there is another file named .docx or .txt or a folder, it will return None.
os.rename(os.path.join(folder_path,i),os.path.join(folder_path,paths[0]+"."+extensions.get(paths[-1]))) #====os.path.join(folder_path,i) joins the folder path and file name
First make a dictionary mapping between the "old" and "new" extensions. From what I could read (and since you have a lot of files) you could have an integrity problem of the extensions... maybe a jjp extension? So the mapping step is quite important...
Second for renaming the file just be careful from which position in the filesystem you run the program. Here a basic solution
import os
extensions = {'jp': 'jpg', 'jpg': 'jpeg', 'mp': 'mp4'}
def rename_files(dir_path, extensions):
files = os.listdir(dir_path)
for file in files:
for ext in extensions: # loop over the old extensions
if file.endswith(ext): # check the extension
file_new = '{}.{}'.format(os.path.splitext(file)[0], extensions[ext])
os.rename(os.path.join(dir_path, file_new)) # rename the files
print('{} --> {}'.format(file, file_new))
dir_of_the_files = '.'
rename_files(dir_of_the_files, extensions)
I have made a file search program which search for the file. it is working fine with searching in current working directory and also inside one folder, however it does not work folder inside folder, I am not getting why? Can anyone please help?
My Code:
import os
files = []
def file_search(file, path=""):
if path == "":
path = os.getcwd()
for item in os.listdir(path):
if os.path.isdir(item):
path = os.path.realpath(item)
file_search(file, path)
elif item == file:
files.append(item)
return files
print(file_search("cool.txt"))
I think it will be simpler if you used glob library.
Example:
import glob
files = glob.glob('**/cool.txt', recursive=True)
New to coding, reading some books and trying to practice. Wrote a program in python3.7 to search through a directory, find all the pdf files and move them to a new folder called 'Reading Materials'.
How could I improve on this code e.g a shorter, more concise and/or efficient script in python?
import os, re, shutil
os.chdir(r'C:\\Users\\Luke\\Documents\\coding\\python\\') #set cwd to the where I want program to run
#create regex to identify pdf files
PDFregex = re.compile(r'''^(.*?) # all text before the file extension
\.{1} #start of file extension
(pdf)$ #ending in pdf''', re.VERBOSE)
Newdir = os.mkdir('Reading Material') #make new directory for files
NewdirPath = os.path.abspath('Reading Material')
print('new directory made at : '+NewdirPath)
#search through directory for files that contain .pdf extension using regex object
for pdf in os.listdir('.'):
mo = PDFregex.search(pdf)
if mo == None: #no pdf's found by regex search
continue #bypass loop
else:
originalLoc = os.path.join(os.path.abspath('.'), pdf) #original file location
newLoc = shutil.move(originalLoc, os.path.join(NewdirPath, pdf)) #move pdf to new folder
print('Moving file "%s" moved to "%s"...' %(pdf, newLoc)) #say what's moving
os.listdir(NewdirPath)
Regexp is overkilled here. os module has various method to help you extract informations about files.
You can use splitext method in os module to find the extension.
Something like this should work :
import os
import shutil
old_dir = 'C:\\Users\\Luke\\Documents\\coding\\python\\'
new_dir = 'Reading Material'
# You should always use underscore_notations to name variables instead of CamelCase (use for ClassNames) see https://www.python.org/dev/peps/pep-0008/
os.makedirs(new_dir, exist_ok=True)
for file_path in os.listdir(old_dir):
if os.path.splitext(file_path)[1] == '.pdf':
shutil.move(file_path, '{0}\\{1}'.format(new_dir, os.path.basename(file_path)))
What I'm trying to do: I'm trying to make a recursive .tar file backup of the directory this python script is run in.
What I currently have:
import os
import zipfile
import datetime
import tarfile
datetime = str( datetime.datetime.now() )
def zipdir(path, zip):
for root, dirs, files in os.walk(path):
for file in files:
zip.write(os.path.join(root, file))
backupdir = raw_input('Which directory should we backup to? \n')
if backupdir :
try:
zipf = zipfile.ZipFile('DrupalInstanceBackup'+datetime+'.zip', mode='w')
zipdir('/Users/localuser/Downloads/backup', zipf)
except Exception as e:
print e
finally:
zipf.close()
What it currently does:
It makes a .zip backup, but when extracted it doesn't show any files.
What Im trying to do:
Can someone help me make this script recursively backup a directory and create a .tar archive of the directory and its files in a recursive manner?
Thank you
The good news is that tarfile supports recursively adding members any work.
with tarfile.open(archive_name + '.tar.gz', mode='w:gz') as archive:
archive.add('/Users/localuser/Downloads/backup', recursive=True)
recursive=True is the default, so you can omit it.