Ziping a File in python and moving it - python-2.7

In the script when I have zip it up a file in say C:/Users/User/Desktop/Folder, it shows up as a zip file in the structure of ZipFile.zip/C:/Users/user/Desktop/Folder instead of just ZipFile.zip/Folder and I can't figure out how to fix it. [Zipping code is lines 21-26]
I'm also trying to move the created zip file to the specified back up device [line 27]
My code is :
import os
import sys
import shutil
import zipfile
import traceback
print ('Welcome to USB Backup Utility')
print ('Created by: TheCryptek')
print ('\nWhat directory would you like to back up?')
print ('Example: C:/users/user/Desktop/Folder')
backUp = raw_input('> ') # Files the user specified to back up
print ('\nWhere would you like to back these files up at?')
print ('Example USB Letter: E:/')
backDevice = raw_input('> ') # Device the user specified to save the back up on.
print ('\nName of the zip file you prefer?')
print ('Example: Backup.zip')
backZip = raw_input('> ') # The name of the zip file specified by the user
print ('\nBackup started...')
if not os.path.exists(backDevice + '/BackUp'): # If the BackUp folder doesn't exist on the device then
os.mkdir(backDevice + 'BackUp') # Make the backup folder on usb device
backZip = zipfile.ZipFile(backZip, 'w') # Not sure what to say for lines 21 - 26
for dirname, subdirs, files in os.walk(backUp):
backZip.write(dirname)
for filename in files:
backZip.write(os.path.join(dirname, filename))
backZip.close()
shutil.move(backZip, backDevice + '/BackUp') # Move the zip files created in working directory to the specified back up device -[ Something is wrong with this can't figure out what ]-
print('Backup finished.')

For shutil.move() you have to give proper source and destination paths.
And in your program,the source path and file object are of same names.so it is calling that object instead it should take the path of file.
import os
import sys
import shutil
import zipfile
import traceback
print ('Welcome to USB Backup Utility')
print ('Created by: TheCryptek')
print ('\nWhat directory would you like to back up?')
print ('Example: C:/users/user/Desktop/Folder')
backUp = raw_input('> ') # Files the user specified to back up
print ('\nWhere would you like to back these files up at?')
print ('Example USB Letter: E:/')
backDevice = raw_input('> ') # Device the user specified to save the back up on.
print ('\nName of the zip file you prefer?')
print ('Example: Backup.zip')
backZip = raw_input('> ') # The name of the zip file specified by the user
print ('\nBackup started...')
if not os.path.exists(backDevice + '/BackUp'): # If the BackUp folder doesn't exist on the device then
os.mkdir(backDevice + 'BackUp') # Make the backup folder on usb device
bkZip = zipfile.ZipFile(backZip, 'w') # Not sure what to say for lines 21 - 26
for dirname, subdirs, files in os.walk(backUp):
bkZip.write(dirname)
for filename in files:
bkZip.write(os.path.join(dirname, filename))
bkZip.close()
#print backZip,backDevice
dest = backDevice + '/BackUp'
#print dest
shutil.move(backZip, dest) # Move the zip files created in working directory to the specified back up device -[ Something is wrong with this can't figure out what ]-
print('Backup finished.')

You have to make an absolute path for it probs.

Related

rename files by omitting numbers form files names error

I try to follow an example in an online course to create a function to change the files name by omitting the numbers from the files name. But I got this error:
os.rename(file_name, file_name.translate(None,"0123456789"))
WindowsError: [Error 2] The system cannot find the file specified
But the code runs fine on the video that I watched
import os
def rename_files():
# (1) get file naems from a folder
file_list = os.listdir(r"C:\prank")
#print (file_list)
saved_path = os.getcwd()
print (" Currnet Wroking Directory is " +saved_path)
os.chdir(r"C:\prank")
# (2) for each file, rename filename
for file_name in file_list:
os.rename(file_name, file_name.translate(None,"0123456789"))
os.chdir (saved_path)
rename_files()
Try this one out, there is no need to change the working directory, its not a good practice. Also if you are renaming files in C: you may have to execute the code as administrator.
import os
def rename_files():
# directoy with the files
directory=r"C:\prank"
# (1) get file names from a folder
file_list = os.listdir(directory) # this is the folder with the files
# (2) for each file, rename filename
for file_name in file_list:
new_name=''.join([s for s in file_name if s not in ['0','1','2','3','4','5','6','7','8','9']]) # remove numbers
os.rename(os.path.join(directory,file_name),os.path.join(directory,new_name))
rename_files()

Python 2.7 and PrettyTables

I am trying to get PrettyTables to work with the following script. I can get it almost to look right but it keeps separating my tables so it is printing 16 separate tables. I need all information in one table that I can sort. I appreciate all the help i can get.
import sys
import os
import datetime
import hashlib
import logging
def getScanPath(): #12
# Prompt User for path to scan
path = raw_input('Please enter the directory to scan: ')
# Verify that the path is a directory
if os.path.isdir(path):
return path
else:
sys.exit('Invalid File Path ... Script Aborted')
def getFileList(filePath):
# Create an empty list to hold the resulting files
pathList =[]
# Get a list of files, note these will be just the names of the files
# NOT the full path
simpleFileNameList = os.listdir(filePath)
# Now process each filename in the list
for eachFile in simpleFileNameList:
# 1) Get the full path by join the directory with the filename
fullPath = os.path.join(filePath, eachFile)
# 2) Make sure the full path is an absolute path
absPath = os.path.abspath(fullPath)
# 3) Make sure the absolute path is a file i.e. not a folder or directory
if os.path.isfile(absPath):
# 4) if all is well, add the absolute path to the list
pathList.append(absPath)
else:
logging.error('A Non-File has been identified')
# 5) Once all files have been identified, return the list to the caller
return pathList
def getFileName(theFile):
return os.path.basename(theFile)
def getFileSize(theFile):
return os.path.getsize(theFile)
def getFileLastModified(theFile):
return os.path.getmtime(theFile)
def getFileHash(theFile):
hash_md5 = hashlib.md5()
with open(theFile, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_md5.update(chunk)
return hash_md5.hexdigest()
# Main Script Starts Here
if __name__ == '__main__':
#Welcome Message
print "\nWelcome to the file scanner\n"
# prompt user for directory path
scanPath = getScanPath()
# Get a list of files with full path
scanFileList = getFileList(scanPath)
# Output Filenames
print "Files found in directory"
for eachFilePath in scanFileList:
fileName = getFileName(eachFilePath)
fileSize = getFileSize(eachFilePath)
lastModified = getFileLastModified(eachFilePath)
hashValue = getFileHash(eachFilePath)
fileModified = (datetime.datetime.fromtimestamp(lastModified))
from prettytable import PrettyTable
pTable = PrettyTable()
pTable.field_names = ["File Name", "File Size", "Last Modified", "Md5 Hash Value"]
pTable.add_row ([fileName, fileSize, fileModified, hashValue])
print (pTable)enter code here
This should show me one big table using all the values from a set directory that the user chooses. This will allow me to sort the table later using prettytables.
I have no experience with prettyTables, but I noticed you have lastModified and fileModified yet only fileModified is used for a column in your table. Are you sure pretty table doesn't have some kind of row limit?

How to open concurrently two files with same name and different extension in python?

I have a folder with multiple couple of files:
a.txt
a.json
b.txt
b.json
and so on:
Using a for loop i want to open a couple of file (a.txt and a.json) concurrently.
Is there a way to do it using the 'with' statement in python?
You could do something like the following which constructs a dictionary keyed by the file name sans extension, and with a count of the number of files matching the required extensions. Then you can iterate over the dictionary opening pairs of files:
import os
from collections import defaultdict
EXTENSIONS = {'.json', '.txt'}
directory = '/path/to/your/files'
grouped_files = defaultdict(int)
for f in os.listdir(directory):
name, ext = os.path.splitext(os.path.join(directory, f))
if ext in EXTENSIONS:
grouped_files[name] += 1
for name in grouped_files:
if grouped_files[name] == len(EXTENSIONS):
with open('{}.txt'.format(name)) as txt_file, \
open('{}.json'.format(name)) as json_file:
# process files
print(txt_file, json_file)
i have two folders of diffrent files one with .jpg and another with.xml this is how i put them into another folder
import os
from pathlib import Path
import shutil
#making the list to store the name
picList=list()
xmlList=list()
#making the directory path
xmlDir = os.listdir('C:\\Users\\%USERNAME%\\Desktop\\img+xml\\XML')
picDir=os.listdir('C:\\Users\\%USERNAME%\\Desktop\\img+xml\\img')
dest=r'C:\Users\%USERNAME%\Desktop\img+xml\i'
#appending the file name to the list
for a in xmlDir:
a=Path(a).stem
xmlList.append(a)
picList.append(a)
#matching and putting file name in destination
for a in xmlList:
for b in picList:
if a==b:
try:
shutil.move(f'C:\\Users\\%USERNAME%\\Desktop\\img+xml\\XML\\{a}.xml',dest)
shutil.move(f'C:\\Users\\%USERNAME%\\Desktop\\img+xml\\img\\{b}.jpg',dest)
except Exception as e:
print(e)

Upload an mp3 files to soundcloud using Python (file name is random)

I'd like to upload an mp3 file from hotfolder without knowing the name of the file. (such as *.mp3)
here's what I tried (to upload specific file / known file name)
import soundcloud
# create client object with app and user credentials
client = soundcloud.Client(client_id='***',
client_secret='***',
username='***',
password='***')
# print authenticated user's username
print client.get('/me').username
mp3_file=('test.mp3')
# upload audio file
track = client.post('/tracks', track={
'title': 'Test Sound',
'asset_data': open(mp3_file, 'rb')
})
# print track link
print track.permalink_url
how can I make the script upload any mp3 file in that folder ? (script and files are located in the same folder)
From the language as written here, it's not precisely clear what you mean by "upload any mp3 file in that folder." Does uploading the first file in the folder satisfy your need, or does it need to be a different file each time the script executes? If the latter, my suggestion is to get a list of files and then randomly select one of them.
To get a list of all files in python,
from os import listdir
from os.path import isfile, join
onlyfiles = [ f for f in listdir(mypath) if isfile(join(mypath,f)) ]
and then to randomly select one of them:
import random
print(random.choice(onlyfiles))
Hope this helps

Zipping a file from a directory and placing it in another Directory

I am trying to set up a program to put my minecraft server world into a zip and place it into another directory on another drive (/media/500gb/MinecraftWorldBackups)
But I keep getting this error
Although the folder doesn't contain a folder or file called 'h'
What do I need to do to fix this I believe it is due to file and folder?
#!/usr/bin/env python
import time, zipfile
while True:
FileName = 'MinecraftBackup_' + str(int(time.time()))
Path = '/home/bertie/Desktop/FeedTheBeastServer/world/'
print(FileName)
Zip = zipfile.ZipFile('/media/500gb/MinecraftWorldBackups/'+FileName+'.zip','w')
for each in Path:
print(each)
try: Zip.write(Path + each)
except IOError: None
Zip.Close()
print('Done')
time.sleep(60)