I wrote a script with Python which allows me to move files according their extension, to another folder , if it is a Music file then the file goes to the Music folder and so on. The thing is that I have to run the program inside the directory even though i coded it to run in the folders I type in, for the program to work properly, if i'm outside the folder it tells me that the file already exist in the folder which is going to be moved, which is not true, so i have to place myself in the folder and run the script for it to work as it was programmed. I'm kinda new here, I was looking if I can find a solution but I couldn't find it, if anyone can help me, I would appreciate it. Here is the code:
import os
import shutil
docs = [
".doc",
".docx",
".odt",
".pdf",
".rtf",
".txt",
".wpd",
".xls",
".xlsx",
".xml",
".ppt",
".pptx",
".pps",
".ppsx",
".odp",
".csv",
".py",
".pyc",
".pyo",
".pyw",
".c",
".cc",
".cxx",
".h",
".hh",
".hpp",
".hxx",
".m",
".mm",
".pl",
".pm",
".pyc",
".pyo",
".rst",
".xhtml",
".yml",
".epub",
]
audio = [".mp3", ".wav", ".wma", ".aac", ".flac", ".ogg"]
images = [" .bmp", ".gif", ".jpg", ".jpeg", ".png", ".psd", ".tiff"]
video = [".avi", ".flv", ".mov", ".mp4", ".mpg", ".rm", ".swf", ".wmv"]
files = [
".7z",
".arj",
".bz2",
".cab",
".gz",
".rar",
".tar",
".tgz",
".zip",
".deb",
".iso",
".rpm",
".msi",
".exe",
".AppImage",
".flatpakref",
]
vpn = [".ovpn"]
fonts = [" .ttf", ".otf", ".woff", ".woff2"]
dir = input("Enter the directory: ")
path=os.listdir(dir)
def is_audio(file):
return os.path.splitext(file)[1] in audio
def is_image(file):
return os.path.splitext(file)[1] in images
def is_video(file):
return os.path.splitext(file)[1] in video
def is_doc(file):
return os.path.splitext(file)[1] in docs
def is_file(file):
return os.path.splitext(file)[1] in files
def is_vpn(file):
return os.path.splitext(file)[1] in vpn
def is_font(file):
return os.path.splitext(file)[1] in fonts
for file in path:
try:
if is_audio(file):
shutil.move(file, "/home/zephyr/Music")
print("Moved " + file + " to Music")
elif is_image(file):
shutil.move(file, "/home/zephyr/Pictures")
print("Moved " + file + " to Pictures")
elif is_video(file):
shutil.move(file, "/home/zephyr/Videos")
print("Moved " + file + " to Videos")
elif is_doc(file):
shutil.move(file, "/home/zephyr/Documents")
print("Moved " + file + " to Documents")
elif is_file(file):
shutil.move(file, "/home/zephyr/Programs")
print("Moved " + file + " to Programs")
except:
print(f"{file} Not Moved {FileExistsError}")
pass
Related
I'm trying to iterate through a dir a select the first file available.
These files look like this:
img_1.png img_2.png img_3.mp4 img_4.png img_5.jpg img_6.mp4
As you can see their names are cohesive but their extensions are different. I'd like the script to iterate through each extension for each number before it moves onto the next, IE:
I assume the best way to go about it is iterating through each file and extention like this: img_1.png img_1.jpg and img_1.mp4, and if neither of the three are available, move to the next file and repeat like img_2.png img_2.jpg and img_2.mp4 until there is an available
Question:
Is it best to iterate through the files and use glob to extend a file path with the extensions? Is there a better method?
This is what I thought would work, but it doesn't:
# Gets number of files in dir
list = os.listdir(folder_path)
number_files = len(list)
# Chooses file from dir
e = 0
for i in range(number_files):
try:
chosen_file = folder_path + "img_" + str(e)
for ext in ('*.jpg', '*.png', '*.mp4'):
full_path = chosen_file.extend(glob(join(chosen_file, ext)))
print (full_path)
#random_file = random.choice(os.listdir(folder_path)) # Chooses random file
except:
e += 1
print ('Hit except')
Are there other files in the folder with different names that you do not want to select or are all the files in the folder of interest? Is all that matters that they have the those 3 extensions or are the names important as well?
If you are only interested in files with those 3 extensions then this code will work
import os
import glob
folder_path = 'test\\'
e = 0
for r,d,f in os.walk(folder_path):
for file in f:
extensions = ['.jpg', '.png', '.mp4']
for ext in extensions:
if file.endswith(ext):
full_path = os.path.join(folder_path, file)
print (full_path)
else:
e += 1
print ('Hit except')
Given:
$ ls /tmp
img_1.png img_1.jpg img_2.png img_4.png img_5.jpg img_3.mp4 img_6.mp4
You can use pathlib and a more targeted glob:
from pathlib import Path
p=Path('/tmp')
for fn in (x for x in p.glob('img_[0-9].*')
if x.suffix in ('.png', '.jpg', '.mp4')):
print(fn)
Prints:
/tmp/img_1.png
/tmp/img_1.jpg
/tmp/img_2.png
/tmp/img_4.png
/tmp/img_5.jpg
/tmp/img_3.mp4
/tmp/img_6.mp4
Answer:
Decided to not use glob and did this instead:
i = 0
for i in range(number_files):
try:
chosen_file = folder_path + "img_" + str(i)
jpg_file = chosen_file + ".jpg"
png_file = chosen_file + ".png"
mp4_file = chosen_file + ".mp4"
if os.path.exists(png_file) == True:
print ('png true')
print (png_file)
break
elif os.path.exists(jpg_file) == True:
print ('jpg true')
print (jpg_file)
break
elif os.path.exists(mp4_file) == True:
print ('mp4 true')
print (mp4_file)
break
except:
i += 1
print ('false')
When I run this it creates a file with a space at the beginning of the filename but I just want it to be the name from the list(without the space), how do I do this?
If I use with open("" + item, "w") as f: i get an error message - IOError: [Errno 2] No such file or directory:
import os
directory_path=os.path.dirname(os.path.abspath(__file__))
selllist='#list-of-files-sell'
buylist='#list-of-files-buy'
sell_list_file_content = open(directory_path + "/" + selllist, "r").read()
buy_list_file_content = open(directory_path + "/" + buylist, "r").read()
sellitems = sell_list_file_content.split("#")
buyitems = buy_list_file_content.split("#")
for item in sellitems:
with open(" " + item, "w") as f:
f.write(" ")
for item in buyitems:
with open(" " + item, "w") as f:
f.write(" ")
You could try to use strip to get rid of the spaces, although '"" + item ' should work. It would be a quick fix, but I suggest you look into why that is happening.
with open( (" " + item).strip(), 'w')
You could also use casting and not have to use quotation marks
with open( str(item), 'w')
Completely new to python so forgive me if this a dumb question.
Part of my working tasks is to upgrade the IOS on various Cisco routers and switches.
The most mind numbing part of this is comparing the pre change config with the post change config.
I use ExamDiff for this but with up to 100 devices each night this gets soul destroying.
Is it possible to get python to open ExamDiff and automatically compare the pre and post checks, saving the differences to a file for each device?
I know I can use the import os command to open ExamDiff but I have no idea how to get ExamDiff to work
Can someone point me in the right direction?
Thanks
I got this..........
Works pretty well
#!/usr/bin/python
import os
path = input("Enter the files location: ")
def nexus():
rootdir = path + os.sep
filelist = os.listdir(rootdir)
if filelist:
for file in filelist:
if 'pre' in file:
prefile = file
postfile = file.replace('pre', 'post')
resultfile = file.replace('pre', 'report')
if postfile in filelist:
prefile = rootdir + prefile
postfile = rootdir + postfile
resultfile = rootdir + resultfile
compare(prefile, postfile, resultfile)
else:
print('No corresponding "post"-file to {0}.'.format(prefile))
else:
print('No files found.')
def compare(file1loc, file2loc, comparefileloc):
with open(file1loc, 'r') as file1:
file1lines = file1.readlines()
file1lines = [x.strip() for x in file1lines] # getting rid of whitespace and breaks
with open(file2loc, 'r') as file2:
file2lines = file2.readlines()
file2lines = [x.strip() for x in file2lines] # getting rid of whitespace and breaks
with open(comparefileloc, 'w') as comparefile:
comparefile.write('===== IN FILE 1 BUT NOT FILE 2 =====\r\n')
for file1line in file1lines:
if not file1line in file2lines:
comparefile.write(file1line + '\r\n')
comparefile.write('\r\n')
comparefile.write('===== IN FILE 2 BUT NOT FILE 1 =====\r\n')
for file2line in file2lines:
if not file2line in file1lines:
comparefile.write(file2line + '\r\n')
if __name__ == '__main__':
nexus()
In a Folder, I have 100 files with extensions '.txt','.doc','.pdf'. I need to rename the files as:
If the filename ends with '.txt' -> replace filename ends with '.jpg'
If the filename ends with '.doc' -> replace filename ends with '.mp3'
If the filename ends with '.pdf' -> replace filename ends with '.mp4'
I have tried this one so far
import os,sys
folder ="C:/Users/TestFolder"
for filename in os.listdir(folder):
base_file, ext = os.path.splitext(filename)
print(ext)
if ext == '.txt':
print("------")
print(filename)
print(base_file)
print(ext)
os.rename(filename, base_file + '.jpg')
elif ext == '.doc':
print("------")
os.rename(filename, base_file + '.mp3')
elif ext == '.pdf':
print("------")
os.rename(filename, base_file + '.mp4')
else:
print("Not found")
To begin with , you can store your mappings in a dictionary, then when you are iterating over your folder, and you find the extension, just use the mapping to make the new file name and save it.
import os
folder ="C:/Users/TestFolder"
#Dictionary for extension mappings
rename_dict = {'txt': 'jpg', 'doc': 'mp3', 'pdf': 'mp4'}
for filename in os.listdir(folder):
#Get the extension and remove . from it
base_file, ext = os.path.splitext(filename)
ext = ext.replace('.','')
#If you find the extension to rename
if ext in rename_dict:
#Create the new file name
new_ext = rename_dict[ext]
new_file = base_file + '.' + new_ext
#Create the full old and new path
old_path = os.path.join(folder, filename)
new_path = os.path.join(folder, new_file)
#Rename the file
os.rename(old_path, new_path)
Under Linux / bash, how can I obtain a plain-text representation of a directory of its contents? (Note that by "plain-text" here I mean "UTF-8").
In other words, how could I "pack" or "archive" a directory (with contents - including binary files) as a plain text file - such that I could "unpack" it later, and obtain the same directory with its contents?
I was interested in this for a while, and I think I finally managed to cook up a script that works in both Python 2.7 and 3.4 -- however, I'd still like to know if there is something else that does the same. Here it is as a Gist (with some more comments):
https://gist.github.com/anonymous/1a68bf2c9134fd5312219c8f68713632
Otherwise, I'm posting a slightly abridged version here (below) for reference.
The usage is: to archive/pack into a .json text file:
python archdir2text-json.py -a /tmp > myarchdir.json
... and to unpack from the .json text file into the current (calling) directory:
python archdir2text-json.py -u myarchdir.json
Binary files are handled as base64.
Here is the script:
archdir2text-json.py
#!/usr/bin/env python
import pprint, inspect
import argparse
import os
import stat
import errno
import base64
import codecs
class SmartDescriptionFormatter(argparse.RawDescriptionHelpFormatter):
def _fill_text(self, text, width, indent):
if text.startswith('R|'):
paragraphs = text[2:].splitlines()
rebroken = [argparse._textwrap.wrap(tpar, width) for tpar in paragraphs]
rebrokenstr = []
for tlinearr in rebroken:
if (len(tlinearr) == 0):
rebrokenstr.append("")
else:
for tlinepiece in tlinearr:
rebrokenstr.append(tlinepiece)
return '\n'.join(rebrokenstr)
return argparse.RawDescriptionHelpFormatter._fill_text(self, text, width, indent)
textchars = bytearray({7,8,9,10,12,13,27} | set(range(0x20, 0x100)) - {0x7f})
is_binary_string = lambda bytes: bool(bytes.translate(None, textchars))
cwd = os.getcwd()
if os.name == 'nt':
import win32api, win32con
def folder_is_hidden(p):
if os.name== 'nt':
attribute = win32api.GetFileAttributes(p)
return attribute & (win32con.FILE_ATTRIBUTE_HIDDEN | win32con.FILE_ATTRIBUTE_SYSTEM)
else:
return os.path.basename(p).startswith('.') #linux-osx
def path_hierarchy(path):
hierarchy = {
'type': 'folder',
'name': os.path.basename(path),
'path': path,
}
try:
cleared_contents = [contents
for contents in os.listdir(path)
if not(
os.path.isdir(os.path.join(path, contents))
and
folder_is_hidden(os.path.join(path, contents))
)]
hierarchy['children'] = [
path_hierarchy(os.path.join(path, contents))
for contents in cleared_contents
]
except OSError as e:
if e.errno == errno.ENOTDIR:
hierarchy['type'] = 'file'
else:
hierarchy['type'] += " " + str(e)
if hierarchy['type'] == 'file':
isfifo = stat.S_ISFIFO(os.stat(hierarchy['path']).st_mode)
if isfifo:
ftype = "fifo"
else:
try:
data = open(hierarchy['path'], 'rb').read()
ftype = "bin" if is_binary_string(data) else "txt"
if (ftype == "txt"):
hierarchy['content'] = data.decode("utf-8")
else:
hierarchy['content'] = base64.b64encode(data).decode("utf-8")
except Exception as e:
ftype = str(e)
hierarchy['ftype'] = ftype
return hierarchy
def recurse_unpack(inobj, relpath=""):
if (inobj['type'] == "folder"):
rpname = relpath + inobj['name']
sys.stderr.write("folder name: " + rpname + os.linesep);
os.mkdir(rpname)
for tchild in inobj['children']:
recurse_unpack(tchild, relpath=relpath+inobj['name']+os.sep)
elif (inobj['type'] == "file"):
rfname = relpath + inobj['name']
sys.stderr.write("file name: " + rfname + os.linesep)
if inobj['ftype'] == "txt":
with codecs.open(rfname, "w", "utf-8") as text_file:
text_file.write(inobj['content'])
elif inobj['ftype'] == "bin":
with open(rfname, "wb") as bin_file:
bin_file.write(base64.b64decode(inobj['content']))
if __name__ == '__main__':
import json
import sys
parser = argparse.ArgumentParser(formatter_class=SmartDescriptionFormatter, description="""R|Command-line App that packs/archives (and vice-versa) a directory to a plain-text .json file; should work w/ both Python 2.7 and 3.4
see full help text in https://gist.github.com/anonymous/1a68bf2c9134fd5312219c8f68713632""")
parser.add_argument('input_paths', type=str, nargs='*', default=['.'],
help='Paths to files/directories to include in the archive; or path to .json archive file')
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('-a', '--archive', action='store_true', help="Interpret input_paths as paths to files/directories, and archive them to a .json file (output to stdout)")
group.add_argument('-u', '--unpack', action='store_true', help="Interpret input_paths as path to an archive .json file, and unpack it in the current directory")
args = parser.parse_args()
if (args.archive):
valid_input_paths = []
for p in args.input_paths:
if os.path.isdir(p) or os.path.exists(p):
valid_input_paths.append(p)
else:
sys.stderr.write("Ignoring invalid input path: " + p + os.linesep)
sys.stderr.write("Encoding input path(s): " + str(valid_input_paths) + os.linesep)
path_hier_arr = [path_hierarchy(vp) for vp in valid_input_paths]
outjson = json.dumps(path_hier_arr, indent=2, sort_keys=True, separators=(',', ': '))
print(outjson)
elif (args.unpack):
valid_input_paths = []
for p in args.input_paths:
if os.path.isdir(p) or os.path.exists(p):
valid_input_paths.append(p)
else:
sys.stderr.write("Ignoring invalid input path: " + p + os.linesep)
for vp in valid_input_paths:
with open(vp) as data_file:
data = json.load(data_file)
for datachunk in data:
recurse_unpack(datachunk)