Wednesday, September 12, 2012

Zip Files & Folders with Python ZipFile

Here is my code to create a zip file using Python's ZipFile module.  The code works for individual files, folders, and wildcards, etc.

Usage:

1. Create a blank  / empty Zip file:

Zip(r'c:\temp\foo.zip')


2. Create a zip file for files and folders

Zip(r'c:\temp\foo.zip', [r'*.txt', r'Folder', r'Folder2\*.txt'])

3. Create a zip file with nice sub directory names

    Assume following directory structure.
        c:\temp
        c:\temp\Apple\Pie.txt
        c:\temp\Orange\Slice.txt
        c:\temp\Banana\Pudding.txt
    Set the current directory to c:\temp & execute following command will create a Zip file with following path names:
    # set current working directory to c:\temp
    Zip(r'c:\temp\foo.zip', [r'c:\temp\Apple', r'c:\temp\Orange', r'c:\temp\Banana'])

    Apple\Pie.txt
    Orange\Slice.txt
    Banana\Pudding.txt
Code:

import collections
import glob
import os
import re
import shutil
import sys
import threading
import time
import zipfile


# Helper function to retrieve files from a list of paths.  Paths can contain wildcards

def FileListFromPathList(PathList=[]):
    if not isinstance(PathList, list):
        PathList = [PathList]

    for path in PathList:
        if not path.strip():
            continue

        path = os.path.abspath(path)
        for found in glob.glob(path):
            if os.path.isfile(found):
                yield found
            else:
                for base, dirs, files in os.walk(found):
                    for file in files:
                        yield os.path.join(base, file)

# Function to do the zipping
def Zip(ZipFilePath, PathList=[], Mode='w', ZipFolderPrefix='', FromCurrentDirectory=True):
    ZipFilePath = Expand(ZipFilePath)

    cwd = os.getcwd()
    rootlen = len(cwd) + 1

    if ZipFolderPrefix:
        ZipFolderPrefix = ZipFolderPrefix + r'\\'

    def MakeZipFolderName(FilePath):
        if FromCurrentDirectory and cwd in FilePath:
            return ZipFolderPrefix + FilePath[rootlen:]
        else:
            return ZipFolderPrefix + os.path.basename(FilePath)

    zipFile = zipfile.ZipFile(ZipFilePath, Mode)

    print r'Zipping to %s' % (ZipFilePath)
    for path in FileListFromPathList(PathList):
        zipPath = MakeZipFolderName(path)
        print r'   Zipping %s' % (zipPath)
        zipFile.write(path, zipPath)

    zipFile.close()

Thursday, August 16, 2012

Wednesday, August 1, 2012

Komodo Edit column mode selection / edit


Column / Rectangular Selection

Rectangular selection is useful in selecting columns and other space or tab delimited text.
PlatformVia MouseVia Keyboard
Windows'Alt'+'left-click' + drag'Alt'+'Shift' + direction key
Mac OS X'Cmd'+'left-click' + drag'Ctrl'+'Shift' + direction key
Linux'Ctrl'+'left-click' + drag'Alt'+'Shift' + direction key
Cut, Copy, Paste and Delete commands will operate on the highlighted block.
Note: On Linux, the default key bindings may conflict with ones used by the window manager. To avoid this, re-map the "Editor: Select Rectangular..." commands in the Key Binding Preferences to unused key combinations.

Column Editing

Once a rectangular selection has been made, text insertion will operate on each line of the selection; the characters will be duplicated on all selected lines.
For example to change "directory-name" in the file list below, select the column containing that name as described above.
Column Selection
Once the column is selected, begin typing. The cursor will appear only at the top line of the selection, but the new text will appear on all subsequent lines within the colum selection.
Column Editing
Press 'Esc' or any direction key to exit column editing mode.
Note: Column selections in areas beyond line endings will not appear correctly. The areas beyond the end of line will not be highlighted, but column editing will still work. Text will be inserted immediately after the longest line in the selection.
With Vi emulation enabled, mouse selection and Vi visual blockwise selection ('Ctrl'+'V') will not trigger column editing. While in Input mode, use 'Alt'+'Shift' with the direction keys to make the column selection, and 'Esc' to exit column editing mode.

Tuesday, July 3, 2012

Override Python dictionary to easily access dictionary entries as an attribute

Accessing python dictionary by attribute instead of [key] is easy if you override the dictionary class and provide the __getattr__ and __setattr__ methods as shown in MyDict class.


Before
old = {}
old['Name'] = 'Daffy'
old['Age'] = 30

After
new = MyDict()
new.Name = 'Micky'
new.Age = 30

print values['Name'], values.Name

print len(values.keys())

class MyDict(dict):
    def __init__(self):
        pass


    def __getattr__(self, name):
        return = self.get(name, '')


    def __setattr__(self, name, value):
        self[name] = value


    def __delattr__(self, name):
        if name in self:
            del self[name]

Python Cheat Sheet

Python Cheat Sheet



Case Insensitive Dictionary search:

1. First create a set with lower case values

dict(zip(map(string.lower,a.keys()),a.values()))







Sunday, July 1, 2012

Never buying another Mac

Man what a crappy OS.  I have never use an OS that just shows the busy icon for no reason.

Mac Book Pro - 15 " Mid 2009
2.53 GB Intel Core Duo
500 GB hard-drive
8GB of RAM

I think I am going to install Windows on it.
1. Spinning pinwheel of death pops up way to much.
2. Takes forever to launch apps, I even upgraded the ram to 8 GB, and it still takes forever
3. Running multiple apps at the same time rarely works
4. The damm keyboard is crazy.  Command, Option, Alt, Shift.  It's enuf to make you crazy.


Thursday, June 28, 2012

node.Js and Express tips

Getting Started with Node.js & Express




Create node.cmd

@if "%_echo%"=="" echo off
call "C:\Program Files (x86)\nodejs\nodejsvars.bat"
PROMPT=[ Node.js $M$P ]$_
set PROMPT=[ Node.js $M$P ]$_
TITLE node 


Friday, May 25, 2012

directory listing excluding files

dir /s /b /a-r-d   | findstr /v /i ".suo$"



FINDSTR [/B] [/E] [/L] [/R] [/S] [/I] [/X] [/V] [/N] [/M] [/O] [/P] [/F:file]
        [/C:string] [/G:file] [/D:dir list] [/A:color attributes] [/OFF[LINE]]
        strings [[drive:][path]filename[ ...]]

  /B         Matches pattern if at the beginning of a line.
  /E         Matches pattern if at the end of a line.
  /L         Uses search strings literally.
  /R         Uses search strings as regular expressions.
  /S         Searches for matching files in the current directory and all
             subdirectories.
  /I         Specifies that the search is not to be case-sensitive.
  /X         Prints lines that match exactly.
  /V         Prints only lines that do not contain a match.
  /N         Prints the line number before each line that matches.
  /M         Prints only the filename if a file contains a match.
  /O         Prints character offset before each matching line.
  /P         Skip files with non-printable characters.
  /OFF[LINE] Do not skip files with offline attribute set.
  /A:attr    Specifies color attribute with two hex digits. See "color /?"
  /F:file    Reads file list from the specified file(/ stands for console).
  /C:string  Uses specified string as a literal search string.
  /G:file    Gets search strings from the specified file(/ stands for console).
  /D:dir     Search a semicolon delimited list of directories
  strings    Text to be searched for.
  [drive:][path]filename
             Specifies a file or files to search.

Use spaces to separate multiple search strings unless the argument is prefixed
with /C.  For example, 'FINDSTR "hello there" x.y' searches for "hello" or
"there" in file x.y.  'FINDSTR /C:"hello there" x.y' searches for
"hello there" in file x.y.

Regular expression quick reference:
  .        Wildcard: any character
  *        Repeat: zero or more occurrences of previous character or class
  ^        Line position: beginning of line
  $        Line position: end of line
  [class]  Character class: any one character in set
  [^class] Inverse class: any one character not in set
  [x-y]    Range: any characters within the specified range
  \x       Escape: literal use of metacharacter x
  \<xyz    Word position: beginning of word
  xyz\>    Word position: end of word

For full information on FINDSTR regular expressions refer to the online Command
Reference.

Thursday, April 19, 2012

Notepad++ failed to load config.xml error

Fix is to reset the following file:

C:\Users\%USERNAME%\AppData\Roaming\Notepad++\config.xml

Contents:

<xml version="1.0" encoding="Windows-1252" ?>

<NotepadPlus>

<GUIConfigs>

<GUIConfig name="ToolBar" visible="yes">standardGUIConfig>

<GUIConfig name="StatusBar">showGUIConfig>

<GUIConfig name="TabBar" dragAndDrop="yes" drawTopBar="yes" drawInactiveTab="yes" reduce="yes" closeButton="no" doubleClick2Close="no" vertical="no" multiLine="no" hide="no" />

<GUIConfig name="ScintillaViewsSplitter">verticalGUIConfig>

<GUIConfig name="UserDefineDlg" position="undocked">hideGUIConfig>

<GUIConfig name="TabSetting" size="4" replaceBySpace="yes" />

<GUIConfig name="AppPosition" x="470" y="4" width="1162" height="993" isMaximized="yes" />

<GUIConfig name="ScintillaPrimaryView" lineNumberMargin="show" bookMarkMargin="show" folderMarkStyle="box" indentGuideLine="show" currentLineHilitingShow="show" Wrap="no" edge="no" edgeNbColumn="100" wrapSymbolShow="hide" zoom="-2" whiteSpaceShow="show" eolShow="hide" lineWrapMethod="aligned" zoom2="-1" borderWidth="2" />

<GUIConfig name="Auto-detection">autoGUIConfig>

<GUIConfig name="CheckHistoryFiles">noGUIConfig>

<GUIConfig name="TrayIcon">noGUIConfig>

<GUIConfig name="RememberLastSession">yesGUIConfig>

<GUIConfig name="NewDocDefaultSettings" format="0" encoding="0" lang="0" codepage="-1" openAnsiAsUTF8="no" />

<GUIConfig name="langsExcluded" gr0="0" gr1="0" gr2="0" gr3="0" gr4="0" gr5="0" gr6="0" gr7="0" langMenuCompact="yes" />

<GUIConfig name="Print" lineNumber="no" printOption="0" headerLeft="$(FULL_CURRENT_PATH)" headerMiddle="" headerRight="$(LONG_DATE) $(TIME)" headerFontName="IBMPC" headerFontStyle="1" headerFontSize="8" footerLeft="" footerMiddle="-$(CURRENT_PRINTING_PAGE)-" footerRight="" footerFontName="" footerFontStyle="0" footerFontSize="9" margeLeft="0" margeTop="0" margeRight="0" margeBottom="0" />

<GUIConfig name="Backup" action="0" useCustumDir="no" dir="" />

<GUIConfig name="TaskList">yesGUIConfig>

<GUIConfig name="SaveOpenFileInSameDir">noGUIConfig>

<GUIConfig name="noUpdate" intervalDays="15" nextUpdateDate="20080426">noGUIConfig>

<GUIConfig name="MaitainIndent">yesGUIConfig>

<GUIConfig name="MRU">yesGUIConfig>

<GUIConfig name="URL">0GUIConfig>

<GUIConfig name="globalOverride" fg="no" bg="no" font="no" fontSize="no" bold="no" italic="no" underline="no" />

<GUIConfig name="auto-completion" autoCAction="0" triggerFromNbChar="1" funcParams="no" />

<GUIConfig name="sessionExt">GUIConfig>

<GUIConfig name="SmartHighLight">yesGUIConfig>

<GUIConfig name="TagsMatchHighLight" TagAttrHighLight="yes" HighLightNonHtmlZone="no">yesGUIConfig>

<GUIConfig name="MenuBar">showGUIConfig>

<GUIConfig name="Caret" width="1" blinkRate="250" />

<GUIConfig name="ScintillaGlobalSettings" enableMultiSelection="no" />

<GUIConfig name="openSaveDir" value="0" defaultDirPath="" />

<GUIConfig name="titleBar" short="no" />

<GUIConfig name="stylerTheme" path="C:\Users\a-cgomes\AppData\Roaming\Notepad++\stylers.xml" />

<GUIConfig name="DockingManager" leftWidth="200" rightWidth="200" topHeight="200" bottomHeight="200">

<PluginDlg pluginName="dummy" id="0" curr="3" prev="-1" isVisible="yes" />

<ActiveTabs cont="0" activeTab="-1" />

<ActiveTabs cont="1" activeTab="-1" />

<ActiveTabs cont="2" activeTab="-1" />

<ActiveTabs cont="3" activeTab="-1" />

<GUIConfig>

<GUIConfigs>

<FindHistory nbMaxFindHistoryPath="10" nbMaxFindHistoryFilter="10" nbMaxFindHistoryFind="10" nbMaxFindHistoryReplace="10" matchWord="yes" matchCase="no" wrap="yes" directionDown="yes" fifRecuisive="yes" fifInHiddenFolder="no" dlgAlwaysVisible="no" fifFilterFollowsDoc="no" fifFolderFollowsDoc="yes" searchMode="0" transparencyMode="1" transparency="150">

<Path name="C:\temp" />

<FindHistory>

<History nbMaxFile="15" inSubMenu="no" customLength="-1">

<File filename="C:\temp\FullRun.log" />

<History>

<ProjectPanels>

<ProjectPanel id="0" workSpaceFile="" />

<ProjectPanel id="1" workSpaceFile="" />

<ProjectPanel id="2" workSpaceFile="" />

<ProjectPanels>

<NotepadPlus>