Using variables recursively in python - python

Can i use variables to set my zip patch inset of entering it manualy
Example part of the code that works fine
if __name__ == '__main__':
zip_folder(r'Monday' ,
r'Monday.zip')
But can i use a variable insted of just a entering the day myself, for this second example i get a "invalid syntax" error
today = "Monday"
today_zip = "Monday.zip"
if __name__ == '__main__':
zip_folder(r today,
r today_zip)
import zipfile
import sys
import os
def zip_folder(folder_path, output_path):
"""Zip the contents of an entire folder (with that folder included
in the archive). Empty subfolders will be included in the archive
as well.
"""
parent_folder = os.path.dirname(folder_path)
# Retrieve the paths of the folder contents.
contents = os.walk(folder_path)
try:
zip_file = zipfile.ZipFile(output_path, 'w', zipfile.ZIP_DEFLATED)
for root, folders, files in contents:
# Include all subfolders, including empty ones.
for folder_name in folders:
absolute_path = os.path.join(root, folder_name)
relative_path = absolute_path.replace(parent_folder + '\\',
'')
print "Adding '%s' to archive." % absolute_path
zip_file.write(absolute_path, relative_path)
for file_name in files:
absolute_path = os.path.join(root, file_name)
relative_path = absolute_path.replace(parent_folder + '\\',
'')
print "Adding '%s' to archive." % absolute_path
zip_file.write(absolute_path, relative_path)
print "'%s' created successfully." % output_path
except IOError, message:
print message
sys.exit(1)
except OSError, message:
print message
sys.exit(1)
except zipfile.BadZipfile, message:
print message
sys.exit(1)
finally:
zip_file.close()
if __name__ == '__main__':
zip_folder(r'Monday',
r'Monday.zip')

You do not need to specify r here:
if __name__ == '__main__':
zip_folder( today, today_zip)
would work fine. r,u etc are qualifiers for strings in python, which is not needed here in your case.

Related

Os.rename Files Overwrite

I am making a Python project that renames multiple files. However, sometimes the files overwrite.
suffixes = ['.pdf', '.epub', '.mobi']
file_list = []
def change_fname(dir_name, part=' (z-lib.org)', action='remove'):
fnames = os.listdir(dir_name)
for suffix in suffixes:
fnames_suffix = [f for f in fnames if f.endswith(suffix)]
for fname in fnames_suffix:
print(f'{action} "{part}" into/from "{fname}"')
if action == 'remove' and fname.endswith(part+suffix):
new_name = fname[:-len(suffix) - len(part)] + suffix
print(f'fname is {fname}')
elif action == 'insert':
new_name = fname[:-len(suffix)] + part + suffix
else:
raise Exception(f'Unknown Action: {action}')
print(new_name)
old_file = os.path.join(dir_name, fname)
new_file = os.path.join(dir_name, new_name)
os.rename(old_file, new_file)
file_to_show = '/Users/ChrisHart/Downloads/test i love you daddy/'
subprocess.call(["open", "-R", file_to_show])
if __name__ == '__main__':
dir_name = '/Users/ChrisHart/Downloads/test i love you daddy/'
try:
change_fname(dir_name, part=' (z-lib.org)', action='remove')
except Exception as ex:
print(ex)
This is my program ^
file (part).pdf
file.pdf
The file will delete " (part)", so we get this
file.pdf
file.pdf
And they overwrite.
file.pdf
How can I fix this overwriting?
I also wrote a script that changes multiple files. Maybe my code helps you understand your problem:
import os
print(os.getcwd()) #Gives you your current directory
os.chdir('/PATH/TO/FILES') #Change directory to the files
for i in os.listdir('/PATH/TO/FILES'):
os.rename(i, i.replace('(z-lib.org)', ' ')) #replaces z-lib with one whitespace
print(i)
I know what you're trying to replace :D ... I did the same thing

Python: can't create subdirectory

I want to apply a test to list of files. The files that past the test should be moved to the directory "Pass"; the others should be moved to the directory "Fail".
Thus the output directory should contain subdirectories "Pass" and "Fail".
Here is my attempt:
if(<scan==pass>) # Working fine up to this point
dest_dir = outDir + '\\' + 'Pass' # The problem is here
print("Pass", xmlfile)
MoveFileToDirectory(inDir, xmlfile, dest_dir)
else:
dest_dir = os.path.dirname(outDir + '\\' + 'Fail')
print("Fail: ", xmlfile)
MoveFileToDirectory(inDir, xmlfile, dest_dir)
However, my code is moving the files to the output directory and not creating the "Pass" or "Fail" subdirectories. Any ideas why?
Use os.path.join(). Example:
os.path.join(outDir, 'Pass')
See this SO post
Also, we don't know what MoveFileToDirectory does. Use the standard os.rename:
os.rename("path/to/current/file.foo", "path/to/new/desination/for/file.foo")
See this SO post
So:
source_file = os.path.join(inDir, xmlfile)
if(conditionTrue):
dest_file = os.path.join(outDir, 'Pass', xmlfile)
print("Pass: ", xmlfile)
else:
dest_file = os.path.join(outDir, 'File', xmlfile)
print("Fail: ", xmlfile)
os.rename(source_file, dest_file)
Create directories exactly once:
import os
labels = 'Fail', 'Pass'
dirs = [os.path.join(out_dir, label) for label in labels]
for d in dirs:
try:
os.makedirs(d)
except EnvironmentError:
pass # ignore errors
Then you could move files into the created directories:
import shutil
print("%s: %s" % (labels[condition_true], xmlfile))
shutil.move(os.path.join(out_dir, xmlfile), dirs[condition_true])
The code exploits that False == 0 and True == 1 in Python.

Python create sqlite DB

I have the current code for a sqlite db creation:
import storage
import os
import audiotools
def store_dir(d):
store = storage.HashStore()
for root, bar, files in os.walk(d):
for filename in files:
filename = root + '/' + filename
try:
store.store_file(filename)
print ("Stored %s% filename")
except audiotools.UnsupportedFile:
print ('Skipping unsupported file %s') % filename
except Exception, e:
print (e)
def main():
d = input('Enter the path to the music directory: ')
store_dir(d)
print ("Done.")
if __name__ == '__main__':
main()
When this code runs I get a syntax error msg. Please help !
Thanks in advance
There are a few things to address here.
First, this line:
print ('Skipping unsupported file %s') % filename
needs to be this:
print ('Skipping unsupported file %s' % filename)
Second, you need to use raw_input here:
d = input('Enter the path to the music directory: ')
which returns a string object, instead of input, which evaluates input as real Python code.
Third, your indentation is off. I'm pretty sure this is just a SO formatting error though.
Finally, you should use os.path.join here:
filename = root + '/' + filename
That isn't an error though, just a tip.
All in all, your code should look like this:
import storage
import os
import audiotools
def store_dir(d):
store = storage.HashStore()
for root, bar, files in os.walk(d):
for filename in files:
filename = os.path.join(root, filename)
try:
store.store_file(filename)
print ("Stored %s% filename")
except audiotools.UnsupportedFile:
print ('Skipping unsupported file %s' % filename)
except Exception, e:
print (e)
def main():
d = raw_input('Enter the path to the music directory: ')
store_dir(d)
print ("Done.")
if __name__ == '__main__':
main()

python unzip files below the root folder

i would like to unzip all the folders and files of an archive below the root folder, i have archive named abc.zip which gives me files as abc/xyz/ abc/123.jpg abc/xyz1/ , i just want to extract xyz/ , 123.jpg and xyz1/ in the CWD
i use below code to extract a file, but would need help on how to omit the root folder of the list
def unzip_artifact( local_directory, file_path ):
fileName, ext = os.path.splitext( file_path )
if ext == ".zip":
Downloadfile = basename(fileName) + ext
print 'unzipping file ' + Downloadfile
try:
zipfile.ZipFile(file_path).extractall(local_directory)
except zipfile.error, e:
print "Bad zipfile: %s" % (e)
return
You have to use a more complex (and therefore more customizable) way to unzip. Instead of using the 'extractall' method, you must extract each files separately with the 'extract' method. Then you will be able to change the destination directory, omitting archive's sub-directories.
Here is your code with the modification you needed :
def unzip_artifact( local_directory, file_path ):
fileName, ext = os.path.splitext( file_path )
if ext == ".zip":
Downloadfile = fileName + ext
print 'unzipping file ' + Downloadfile
try:
#zipfile.ZipFile(file_path).extractall(local_directory) # Old way
# Open the zip
with zipfile.ZipFile(file_path) as zf:
# For each members of the archive
for member in zf.infolist():
# If it's a directory, continue
if member.filename[-1] == '/': continue
# Else write its content to the root
with open(local_directory+'/'+os.path.basename(member.filename), "w") as outfile:
outfile.write(zf.read(member))
except zipfile.error, e:
print "Bad zipfile: %s" % (e)
return

python rename files not working as I expected

I am trying to rename all the files in a directory making multiple changes on each file in order to make files names internet friendly. It works correctly for a few replacements and then it says file not found. I though that if I slowed it down with time.sleep() it would work, but this seems to have no effect (other than being slow). In some cases I can run the script many times and accomplish the goal, but in some cases it completes without error but the changes are not made. Any suggestions would be appreciated.
import os, glob, time
path = os.getcwd()
dirlist = glob.glob('*.pdf')
for filename in dirlist:
os.rename(os.path.join(path, filename), os.path.join(path, filename.replace(' ', '_')))
os.rename(os.path.join(path, filename), os.path.join(path, filename.lower().encode('utf8')))
os.rename(os.path.join(path, filename), os.path.join(path, filename.replace(' (', '-')))
os.rename(os.path.join(path, filename), os.path.join(path, filename.replace(')', '')))
os.rename(os.path.join(path, filename), os.path.join(path, filename.replace(',', '')))
os.rename(os.path.join(path, filename), os.path.join(path, filename.replace('_-_', '-')))
filename.replace() returns a new string - it does not change filename in any way. So filename will become outdated after renaming a file and cause a file not found error next time it is used.
Try something like this:
import os, glob, time
def new_filename(filename):
return filename.replace(' ', '_').lower().encode('utf8').replace(' (', '-') \
.replace(')', '').replace(',', '').replace('_-_', '-')
path = os.getcwd()
dirlist = glob.glob('*.pdf')
for filename in dirlist:
os.rename(os.path.join(path, filename), os.path.join(path, new_filename(filename)))
usage = '''
$python slug_dir.py DIR
'''
from os import rename, walk
from os.path import join, isdir, splitext
from slugify import slugify
def rename_files(dir_path):
for path, subdirs, files in walk(dir_path):
for fname in files:
filename, extension = splitext(fname)
s = slugify(filename)
newname = s+extension
try:
oldpath = join(path, fname)
newpath = join(path, newname)
print rename(oldpath, newpath)
print 'Rename: ', oldpath, '->', newpath
except Exception as e:
print 'Error triying rename: ', fname, '->', newname
raise e
def main():
dirname = sys.argv[1]
if not isdir(dirname):
print usage
sys.exit(1)
rename_files(dirname)
if __name__ == '__main__':
main()

Categories