Using filters in pyGtk - python-2.7

I am writing a script to display a GUI in which certain files can be chosen. I am using pyGtk and as of now, my code can display all the zip files. I want to add another filter to display only the zip files with the latest date.
Below is my function that displays only zip files.
def open_file( self, w, data=None):
d = gtk.FileChooserDialog( title="Select a file",
parent=self.window,
action=gtk.FILE_CHOOSER_ACTION_OPEN,
buttons=("OK",True,"Cancel",False)
)
#create filters
filter1 = gtk.FileFilter()
filter1.set_name("All files")
filter1.add_pattern("*")
d.add_filter(filter1)
filter2 = gtk.FileFilter()
filter2.set_name("Zip files")
filter2.add_pattern("*.zip")
d.add_filter(filter2)
ok = d.run()
if ok:
import os
fullname = d.get_filename()
dirname, fname = os.path.split( fullname)
size = "%d bytes" % os.path.getsize( fullname)
text = self.label_template % (fname, dirname, size)
else:
text = self.label_template % ("","","")
self.label.set_label( text)
d.destroy()
Is there a way I can choose a filter to display only the latest zip files in a each folder?
Thanks in advance for your help!

Instead of using filter2.add_pattern("*.zip") use filter2.add_pattern("filename")where filename is the name of the file with the latest date. You can write a function that would return a list with file names of the latest zip file.

Related

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 add file size next to the files name?

I'm trying to export all files according to their extensions and add the size next to them.
import glob2
ext = raw_input("extension:")
ext = "*." + ext
print glob2.glob(ext)
How can I add the file size to the list?
Use os.stat() to find out file metadata (size, date created, etc). It's not clear to me what you mean by next to them so this code produces a list of tuples, [(filename,filesize), ... ].
import glob2
import os
ext = raw_input("extension:")
ext = "*." + ext
filenames = glob2.glob(ext)
filenames_with_sizes = [(filename, os.stat(filename).st_size) for filename in filenames]
print filenames_with_sizes
If you want a pretty list that is nice to print but not amenable to computation then you can do
filenames_with_sizes = ["%-40.40s %d" % (filename, os.stat(filename).st_size) for filename in filenames]

Giving multiple file names as link to Tkinter GUI in python and opening with default application

#python version 2.7.11
import os
from Tkinter import *
fileName = "Nothing" #fileName is required so that the callback function can link the current file name with button click
def callback(event):
#os.startfile() works only on windows machine
os.startfile(fileName) #opens the fileName with its default application (in my case a pdf viewer)
def makeLink(file):
global fileName
fileName = file
link = Label(textbox, text=fileName, fg="blue", cursor="hand2")
link.pack()
link.bind("<Button-1>", callback)
oldDir = os.getcwd()
newDir = os.chdir("pdf folder") #pdf folder contains some pdf files
root = Tk()
textbox = Text(root)
textbox.pack()
allFiles = os.listdir(os.getcwd()) #makes a list of files present in current directory
for file in allFiles:
makeLink(file)
root.mainloop()
os.chdir(oldDir)
I want to select the files of a folder (in above code it's pdf folder) containing some pdf files and display them as a link in GUI window. When pressed on the link, the file should open with it's default application (so the pdf file should open with default pdf viewer). My code is displaying the file names of every file in the "pdf folder" as link. But on clicking on every link, the last file of the folder is opening. Can someone correct the code so that every link opens it's own file. I searched everywhere but found nothing on this topic.
This is exactly what you have coded so far. You're making fileName global and then setting fileName = file where the last assignment will be the last item in your loop. So, this is why it is opening the last file. If you want a user to be able to select options from these I'd suggest a combobox or some other widget that takes the list of filenames as the options. You can then bind on <<ComboboxSelected>> to call your makeLink function.
you should really also rename file. file is a built in.
This problem can surely be done by combobox but when i have many pdf files then every file is placed in a combobox which is not a good way to interact.
Here I have taken two count variables ---- one is global count and one localCount. The localCount is required to remember the count of which file is to be opened.
from Tkinter import *
import os
def callback(count):
os.system("open "+fileNames[count])
def makeLink(files):
localCount = count
link = Button(frame1, text=(count , files), bg="light blue", cursor="hand2", command=lambda: callback(localCount))
link.pack()
oldDir = os.getcwd()
newDir = os.chdir("pdf folder")
fileNames = os.listdir(os.getcwd())
root = Tk()
frame1 = Frame(root)
frame1.pack()
count = 0
for files in fileNames:
makeLink(files)
count += 1
root.mainloop()
os.chdir(oldDir)

shutil.make_archive creates zip file , but skips empty directories

Im not sure what im doing wrong, but what i need is to create a zip file with all files and folders ( empty or not ) of a given directory. So, at the moment i have this simple code that "works" but it doens't add empty folders :|
content of c:\temp\trashtests
c:\temp\trashtests\a\a.txt
c:\temp\trashtests\b\b.txt
c:\temp\trashtests\c
c:\temp\trashtests\d
Current code:
class ZipTools:
"""
Zip tools
"""
def __init__(self, target_path=None, zip_name=None):
self.path = target_path
self.zip_name = zip_name
def create_zip(self):
shutil.make_archive(self.zip_name, format='zip', root_dir=self.path)
execution:
ab = self.ZipTools('c:\temp\trashtests', 'c:\test\a.zip')
ab.create_zip()
The output is a zip file only with:
\a\a.txt
\b\b.txt
So, how can i create a zip file with all contents of a given directory using shutils? If not, how could i do it using zipfile?
Thanks in advance.
EDIT:
As sugested by J.F. Sebastian, i tried the solution of this question but it didn't worked since it created a zip file with the following structure:
File: a.zip
Content:
c:
a\a.txt
b\b.txt
I'm still trying to figure it out a solution :)
I was able to solve this problem using using this code:
An important note, this code works for what i need, which is:
Zip an existing folder with the same name of the zip file to create.
import os
import sys
import zipfile
class ZipTools:
"""
Zip tools
"""
def __init__(self, folder_path=None, pkg_zip=None):
self.path = folder_path
self.zip_name = pkg_zip
self.temp_dir = 'c:\\temp'
self.archive = '{p}\\{z}'.format(p=self.temp_dir, z='a.zip')
def zip(self):
parent_folder = os.path.dirname(self.path)
# Retrieve the paths of the folder contents.
contents = os.walk(self.path)
try:
zip_file = zipfile.ZipFile(self.archive, 'w', zipfile.ZIP_DEFLATED)
for root, folders, files in contents:
# Include all subfolders, including empty ones.
for folder_name in folders:
ab_path = os.path.join(root, folder_name)
rel_path = ab_path.replace(parent_folder + '\\' + self.zip_name, '')
print rel_path
zip_file.write(ab_path, rel_path)
for file_name in files:
ab_path = os.path.join(root, file_name)
rel_path = ab_path.replace(parent_folder + '\\' + self.zip_name, '')
zip_file.write(ab_path, rel_path)
except zipfile.BadZipfile, message:
print message
sys.exit(1)
finally:
zip_file.close()
if __name__ == '__main__':
ab = ZipTools('c:\\temp\\trashtests', 'a.zip')
ab.zip()

Downloading data from website

I use the following code for downloading two files in a folder from a website.
I want to download some files that contain "MOD09GA.A2008077.h22v05.005.2008080122814.hdf" and "MOD09GA.A2008077.h23v05.005.2008080122921.hdf" in the page. But I don't know how to select these files. The code below download all the files, but I only need two of them.
Does anyone have any ideas?
URL = 'http://e4ftl01.cr.usgs.gov/MOLT/MOD09GA.005/2008.03.17/';
% Local path on your machine
localPath = 'E:/myfolder/';
% Read html contents and parse file names with ending *.hdf
urlContents = urlread(URL);
ret = regexp(urlContents, '"\S+.hdf.xml"', 'match');
% Loop over all files and download them
for k=1:length(ret)
filename = ret{k}(2:end-1);
filepathOnline = strcat(URL, filename);
filepathLocal = fullfile(localPath, filename);
urlwrite(filepathOnline, filepathLocal);
end
Try the regexp with tokens instead:
localPath = 'E:/myfolder/';
urlContents = 'aaaa "MOD09GA.A2008077.h22v05.005.2008080122814.hdf.xml" and "MOD09GA.A2008077.h23v05.005.2008080122921.hdf.xml" aaaaa';
ret = regexp(urlContents , '"(\S+)(?:\.\d+){2}(\.hdf\.xml)"', 'tokens');
%// Loop over each file name
for k=1:length(ret)
filename = [ret{k}{:}];
filepathLocal = fullfile(localPath, filename)
end