Python practice: find how many files of each type (extension) exist in a given directory

#! usr/bin/env python3
# by lorenzo - 02/10/2017
# how many files of each type (extension) exist in a given directory?

import os, sys, operator

print("Enter directory where you want to search in:")
location = input()

if not os.path.isdir(location):
    print("You have to enter the address of a directory!")
    sys.exit()

myExt = {}

for folderName, subfolders, filenames in os.walk(location):
    for filename in filenames:
        fileName, fileExt = os.path.splitext(os.path.join(folderName, filename))
        if fileExt in myExt:
            myExt[fileExt] += 1
        else:
            myExt[fileExt] = 1

# descending order based on number of files for each extension, remove reverse=True for ascending order
# if you want to sort based on names of extensions (alphabetical order), use key=operator.itemgetter(0)
myDict = sorted(myExt.items(), key=operator.itemgetter(1), reverse=True) 
for x in myDict:
    print("Extension: " + x[0] + "; number of files with this extension: " + str(x[1]))

Comments about the code are welcome.

Python practice: handling command-line arguments (with sys.argv module)

#! usr/bin/env python3
# by lorenzo - 27/09/2017
# handling command-line arguments with sys.argv (practice)
# the script prints to the screen whatever command-line arguments one gives it;
# running the script in the shell with the command:
# python3 commandLine.py hello, world!
# returns: hello, world!

import sys

if len(sys.argv) > 1:
    print(' '.join(sys.argv[1:]))

Comments about the code are welcome.

ABSP, Ch 10, Practice Project

My solution to the Practice Project in Chapter 10 of the excellent book “Automate the Boring Stuff with Python” (ABSP)

import random
guess = ''
while guess not in ('heads', 'tails'):
    print('Guess the coin toss! Enter heads or tails:')
    guess = input()
toss = random.randint(0, 1) # 0 is tails, 1 is heads
if toss == 0:
    toss = 'tails'
else:
    toss = 'heads'
if toss == guess:
    print('You got it!')
else:
    print('Nope! Guess again!')
    guess = input()
    if toss == guess:
       print('You got it!')
    else:
        print('Nope. You are really bad at this game.')

Comments about the code are welcome.

Python practice: removing duplicate files

#! usr/bin/env python3
# find duplicates of a file specified by the user,
# in a directory specified by the user

import os, sys, filecmp

print("Enter location of the file of which you want to find duplicates of:")
location = input()

if not os.path.isfile(location):
    print("Enter the location of a file!")
    sys.exit()

fileName, fileExtension = os.path.splitext(location)

print("In which directory do you want to search for duplicate files?")
myLocation = input()

if not os.path.isdir(myLocation):
    print("Enter the address of a directory!")
    sys.exit()

for folderName, subfolders, filenames in os.walk(myLocation):
    for filename in filenames:
        if filename.endswith(fileExtension):
            if filecmp.cmp(location, os.path.join(folderName,filename)):
                print("FILES " + location + " and " + filename + " seem equal")
                print("Do you want to delete " + os.path.join(folderName,filename) + " ? (y/n)")
                choice = input()
                if choice == "y":
                    os.unlink(filename)
                    continue
                else:
                    continue

Comments about the code are welcome.

ABSP, Ch 9, Practice Project #3

My solutions to the Practice Project #3 in Chapter 9 of the excellent book “Automate the Boring Stuff with Python” (ABSP)

#! usr/bin/env python3
# by lorenzo - 21/09/2017
# filling in the gaps - program that finds all files with a given prefix, 
#                       such as spam001.txt, spam002.txt, and so on,
#                       in a single folder, locates any gaps 
#                       in the numbering (such as if there is a spam001.txt and #                       spam003.txt but no spam002.txt) and subsequently
#                       renames all the later files to close this gap.                       

import os, sys, shutil

print('Enter location of folder to search in:')
myFolder = os.path.abspath(input())
if not os.path.exists(myFolder):
    print("This path doesn't exist!")
    sys.exit()

print('Enter name part of prefix of the files:')
fileName = input()

print('From which number should the numbering of the files start?')
nStart = int(input())

print('At which number should the numbering of the files end?')
nStop = int(input())

print('How many digits in numbering? (ex. 010 has three digits)')
nDig = int(input())

listOfFiles = []
for i in range(nStart, nStop + 1):    
    nZero = nDig - len(str(i))    
    currentFile = fileName + nZero * '0' + str(i)
    listOfFiles.append(currentFile)

os.chdir(myFolder)
myList = []
for thisFile in os.listdir():
    if thisFile in listOfFiles:
        myList.append(thisFile)
myList.sort()    
for i in range(len(myList)):
        if listOfFiles[i] != myList[i]:
            shutil.move(myList[i], listOfFiles[i])
#! usr/bin/env python3
# by lorenzo - 21/09/2017
# filling in the gaps (alternative version)
# program that finds all files with a given prefix, such as spam001.txt, 
# spam002.txt, and so on, in a single folder, locates any gaps 
# in the numbering (such as if there is a spam001.txt and spam003.txt 
# but no spam002.txt) and subsequently creates appropriately named files
# to close this gap.
                                   
import os, sys

print('Enter location of folder to search in:')
myFolder = os.path.abspath(input())
if not os.path.exists(myFolder):
    print("This path doesn't exist!")
    sys.exit()

print('Enter name part of prefix of the files:')
fileName = input()

print('From which number should the numbering of the files start?')
nStart = int(input())

print('At which number should the numbering of the files end?')
nStop = int(input())

print('How many digits in numbering? (ex. 010 has three digits)')
nDig = int(input())

listOfFiles = []
for i in range(nStart, nStop + 1):    
    nZero = nDig - len(str(i))    
    currentFile = fileName + nZero * '0' + str(i)
    listOfFiles.append(currentFile)
os.chdir(myFolder)
for myFile in listOfFiles:
    if myFile not in os.listdir():
        thisFile = open(myFile, 'w')
        thisFile.close()
    else:
        continue
#! usr/bin/env python3
# by lorenzo - 21/09/2017
# added challenge - program that can insert gaps into numbered files
#                   so that a new file can be added.

import os, sys, shutil

def Add(myString, numToAdd):
    numZeros = 0
    aNumber = []
    aString = []
    for ch in myString:
        if ch.isdecimal():
            aNumber.append(ch)
        else:
            aString.append(ch)
    
    for i in range(len(aNumber)):
        if aNumber[i] == 0:
            numZeros += 1
            del aNumber[i]
        else:
            break
        
    myNumber = ''.join(aNumber)
    thisNumber = int(myNumber) + numToAdd
    strNumb = str(thisNumber)
    finalList = aString[:]
    zeros = numZeros - (len(str(thisNumber))-len(myNumber))
                       
    for num in range(zeros):
                        finalList.append('0')

    for j in range(len(strNumb)):
                        finalList.append(strNumb[i])

    returnStr = ''.join(finalList)
    return returnStr
                           
print('Enter location of folder to search in:')
myFolder = os.path.abspath(input())
if not os.path.exists(myFolder):
    print("This path doesn't exist!")
    sys.exit()

print('Enter prefix of the files:')
fileName = input()

print('Enter complete name of the file from which you want to add spaces:')
fileStart = input()

print('How many spaces do you want between this file and the next one?')
nSpace = int(input())

os.chdir(myFolder)
myList = []
for thisFile in os.listdir():
    if thisFile.startswith(fileName) and thisFile[-1].isdigit():
        myList.append(thisFile)
myList.sort()
myIndex = myList.index(fileStart)
thisList = myList[myIndex+1:]

for myFile in thisList:
    os.rename(myFile, Add(myFile,nSpace))

Comments about the code are welcome.

ABSP Ch 9, Practice Project #1

My solution to the Practice Project #1 in Chapter 9 of the excellent book “Automate the Boring Stuff with Python” (ABSP)

#! usr/bin/env python3
# by lorenzo - 21/09/2017
# selective copy - program that walks through a folder tree,
#                  searches for files with a certain file extensons
#                  and then copies them into a new folder

import os, sys, shutil

print("Enter file extension you want to search for (ex:.pdf):")
extension = input()
print("Enter location of the folder you want to search in:")
location = input()
print("Enter location of the folder where you want to place the files found:")
copyLoc = input()

if not os.path.exists(location):
    print("Location to search in does not exist!")
    sys.exit()

if not os.path.exists(copyLoc):
    print("Location to copy files does not exist!")
    sys.exit()

for folderName, subfolders, filenames in os.walk(location):
    for filename in filenames:
        if filename.endswith(extension):
            shutil.copy(os.path.join(folderName,filename),copyLoc)

Comments about the code are welcome.

ABSP Ch 9, Practice Project #2

My solution to the Practice Project #2 in Chapter 9 of the excellent book “Automate the Boring Stuff with Python” (ABSP)

#! usr/bin/env python3
# by lorenzo - 21/09/2017
# deleting unneeded files - program that walks through a folder tree
#                           and searches for files that have a file size
#                           larger than some threshold determined by the user,
#                           tells the user where these files are and asks
#                           whether the user wants to remove them or not.

import os, sys, send2trash

print("Enter location where you want to search for large files:")
location = input()

if not os.path.isdir(location):
    print("This directory does not exist!")
    sys.exit()

print("Enter threshold (in bytes) for files size:")
threshold = int(input())

choice = ""
for folderName, subfolders, filenames in os.walk(location):
    for filename in filenames:
        if os.path.getsize(os.path.join(folderName, filename)) >= threshold:
            print("Found file with size over threshold:" + os.path.join(folderName, filename))
            print("Do you want to delete it? (y/n)")
            choice = input()
            if choice == "y":
                send2trash.send2trash(os.path.join(folderName, filename))
            else:
                continue

Comments about the code are welcome.

ABSP, Ch 8, Practice Project #3

My solution to the Practice Project #3 in Chapter 8 of the excellent book “Automate the Boring Stuff with Python” (ABSP)

#! usr/bin/env python3
# by lorenzo - 18/08/2017
# regex search - program that opens all .txt files in a folder
#                and searches for any line that matches a user-supplied regex.
#                The results are printed to the screen

import re, os

def addToList(list1, list2):
    for i in range(len(list1)):
        list2.append(list1[i])

print('Enter a regular expression:')
myRegex = input()
thisRegex = re.compile(myRegex)

location = ''
print('Enter directory you want to search in:')
location = input()
os.chdir(location)
myFiles = os.listdir(location)
myList = []
for myFile in myFiles:
    if myFile.endswith('.txt'):
        thisFile = open(myFile, 'r')
        myContent = thisFile.read()
        thisFile.close()
        listToAdd = thisRegex.findall(myContent)
        addToList(listToAdd, myList)

for match in myList:
    print(match, sep = ' ')

Comments about the code are welcome.

ABSP, Ch 8, Practice Project #2

My solution to the Practice Project #2 in Chapter 8 of the excellent book “Automate the Boring Stuff with Python” (ABSP)

#! usr/bin/env python3
# by lorenzo - 17/08/2017
# mad libs - program that reads in text files and lets the user add their own text 
#                    anywhere the word ADJECTIVE, NOUN, ADVERB, or VERB appears in the text file.

def listToString(aList):
    text = ''
    for i in range(len(aList)):
        text += aList[i]
    return text

def Replace(aList, length):
    for i in range(length):
        del aList[-1]

def addToList(aString, aList):
    for i in range(len(aString)):
        aList.append(aString[i])
    return aList

print("Enter location of file to read:")
location = input()
myFile = open(location, 'r')
myContent = myFile.read()
myFile.close()
myList = []

for i in range(len(myContent)):
    myList.append(myContent[i])
    aPiece = listToString(myList) 
    
    if aPiece.endswith('ADJECTIVE'):
        print('Enter an adjective:')
        adjective = input()
        Replace(myList, 9)
        addToList(adjective, myList)
 
    elif aPiece.endswith('NOUN'):
        print('Enter a noun:')
        noun = input()
        Replace(myList, 4)
        addToList(noun, myList)        
 
    elif aPiece.endswith('ADVERB'):
        print('Enter an adverb:')
        adverb = input()
        Replace(myList, 6)
        addToList(adverb, myList)        

    elif aPiece.endswith('VERB'):
        print('Enter a verb:')
        verb = input()
        Replace(myList, 4)
        addToList(verb, myList)         

print(listToString(myList))
thisFile = open('madlibs.txt', 'w')
thisFile.write(listToString(myList))
thisFile.close()

Comments about the code are welcome.

ABSP, Ch 8, Practice Project #1

My solution to the Practice Project #1 in Chapter 8 of the excellent book “Automate the Boring Stuff with Python” (ABSP)

#! usr/bin/env python3
# by lorenzo - 17/08/2017
# mcb.pyw - Saves, deletes and loads pieces of text to the clipboard.
# Usage: python3 mcb.pyw save <keyword> - Saves clipboard to keyword.
#        python3 mcb.pyw <keyword> - Loads keyword to clipboard.
#        python3 mcb.pyw list - Loads all keywords to clipboard.
#        python3 mcb.pyw delete <keyword> - Delete keyword from clipboard
#        python3 mcb.pyw delete - Delete all keywords from clipboard

import shelve, pyperclip, sys

mcbShelf = shelve.open('mcb')

# Save clipboard content.
if len(sys.argv) == 3:
    if sys.argv[1].lower() == 'save':
        mcbShelf[sys.argv[2]] = pyperclip.paste()
    elif sys.argv[1].lower() == 'delete':
        del mcbShelf[sys.argv[2]]

elif len(sys.argv) == 2:
# List keywords and load content.
    if sys.argv[1].lower() == 'list':
        pyperclip.copy(str(list(mcbShelf.keys())))
    if sys.argv[1].lower() == 'delete':
        mcbShelf.clear()
    elif sys.argv[1] in mcbShelf:
        pyperclip.copy(mcbShelf[sys.argv[1]])

mcbShelf.close()

Comments about the code are welcome.