Friday, January 18, 2019

Python Code Snippets #10

Python Newb Code Snippets #10

shambles python newb code-snippets-logo

46-Store and retrieve a variable to a text file

This has obvious uses, saving a high score position in a game for example.  I used this code in my HI-Lo card game to do exactly that.  In the source code I have added a lot of comments to help beginners understand what is going on.  I also added a line to open the text file in notepad just to show what was happening and some print statements, these can all be removed quite easily, (and the “import os”), and the two short load and save routines can go in their own functions.46-python-code-snippets-save-variable-to-text-file

Double click inside source code box to select all

'''
   Save and load variable to a text file
   for later retrieval

   By Steve Shambles Dec 2018
   https://stevepython.wordpress.com
'''
import os

# Example variable
HIGH_SCORE = 1768

# Save the variable HIGH_SCORE to a file named "high_score.txt".
# Change as required.

with open("high_score.txt", 'w') as contents:
    # Need to convert to string to save.
    SAVE_IT = str(HIGH_SCORE)
    contents.write(SAVE_IT)
    print("saved")

# Load back the variable.
with open("high_score.txt", 'r') as contents:
    SAVED_HIGH_SCORE = contents.read()

    # Convert back to to integer.
    if SAVED_HIGH_SCORE > "":
        HIGH_SCORE = int(SAVED_HIGH_SCORE)
        print("Loaded...", HIGH_SCORE)

# Display high_score text in notepad.
os.startfile('high_score.txt')

# Note: PEP8 advises that constants should be all
# UPPER_CASE, this explains why three of my variables
# are so.

47-Randomly shuffle the contents of a string

This bit of code was used in my Bletchley game.  When the computer marked the players pegs it was essential it should be displayed in a random order, otherwise the breaking of the code would be very easy.

As the markers in my game were stored in a simple string I used the string_utils .shuffle method, which I found by Googling for a solution.  String_utils can do lots of other string related stuff, including tons of string checking methods and all quite straight-forward to use, so it may be worth your while checking out the link.

I will most definitely be spending a little time looking at what I can get out of this cool module and if it works for me I will add it to my favourite modules list alongside pyautogui, Pylint and Pyinstaller.

47-python-code-snippets-randomly-shuffle-striing

'''
    Randomly shuffle a string
    Steve Shambles Jan 2019
    https://stevepython.wordpress.com
'''

import string_utils

OUT_COME = "12345"

# Randomly shuffle "OUT_COME" string.
SHUFF = (string_utils.shuffle(OUT_COME))

# Display shuffled up string, note that original
# string still intact in "OUT_COME".
print(SHUFF)

48. Most common words used in a text file

This does a similar, but better, job than snippet 29.  I came across this new snippet whilst browsing around on the Python forum.  I made a few small changes, and gave the code a good PEP8-ing.

The code below loads in a text file called “test.txt” from the current directory, (you may want to change that of course), counts all the words in the file, and then arranges and prints out a list of the most common words used in that file.

You can stipulate how deep you want to count, the example code is set to show the top ten words, but you can set that to anything you want.

I am not going to pretend that I understand what the f-string is doing in the final line, looks gobbledygook to me. 🙂

It would be awesome if we could make it ignore STOP words.  E.g: is, at, the, I, to, a, was, we, for etc.  Then this could be used to look at keyword usage.

python-code-snippets-most-common-words-in-text-file

'''
   Most common words used in a text file.

   For more snippets:
   https://stevepython.wordpress.com/
'''

from collections import Counter
import re

# Loads in a text file called test.txt from current dir.
with open('test.txt') as f:
    TEXT = f.read().lower()

WORDS = re.findall('\w+', TEXT)
TOP_WORDS = Counter(WORDS).most_common(10) # Change the 10 to whatever you like
for word, count in TOP_WORDS:
    print(f'{word:":^4} {count:>4}')

49. Empty Windows Recycle bin

A nice simple one now.  This just empties the trash from the Recycle bin, (Windows only).  This uses the winshell module, so unless you already have that installed you will need to do a “Pip install winshell”, in the usual place.

Just like string_utils, I really like the look of this module, it’s packed with tons of Windows system related methods that could turn out to be very useful for my future projects.  I haven’t had time to take a deep dive yet, as the documentation is huge, but I plan to as soon as possible.

The following snippet is a very simple example of of using Winshell.

I put the try-except block in because if the recycle bin is already empty it produces the error

pywintypes.com_error: (-2147418113, ‘Catastrophic failure‘”,

which sounds like pretty serious doodah stuff to me.

The only problem is, I do not know what exception error I should use, so I used a bare except, which is severely frowned upon by our masters at Python Towers.  If anyone knows what I should of put there, give me a shout please.

See the in-code comments for more details on changing some attributes of the call.

python-code-snippets-empty-recycle-bin

'''
Empty Windows Recycle Bin

You may need to "Pip install winshell"

Steve Shambles Jan 2019

https://stevepython.wordpress.com/
'''

import winshell

# The try-except block captures the error produced
# if the recycle bin is found to be already empty.

# You can change the bool False and True statements to either turn on or off
# the following: confirm yes\no dialog, progress bar, sound effect.

try:
    winshell.recycle_bin().empty(confirm=False, show_progress=False, sound=True)
    print("Recycle bin emptied")

except:
    print("Recycle bin already empty")

50. Get image type from header

The final snippet (for now), examines an image file by looking at the header data rather than looking at its file extension, which can easily be wrong or missing.

I had exactly this problem with my Reddit Image Grabber program, it downloaded images with no file extension, as it turned out the following solution couldn’t help in that particular situation, but I never forgot the simple little module, called imghdr, which is built into Python, so no install required.

To save you Python lovelies some messing about, I have inserted a file selector into the code for easy selection of an image from your drive, and a quick way of testing several image formats, if that floats your boat.

Imghdr covers just about every image format I can think of.  For the record, there is also the built in module sndhdr that does the same with sound files.

python-code-snippets-get-image-type-from-header

'''

   Inspect header of image file to determine image type

   Steve Shambles Jan 2019

   For more snippets:
   https://stevepython.wordpress.com/

'''

from tkinter import Tk, filedialog
import imghdr

# Stop naff unused Tk GUI window showing.
ROOT = Tk()
ROOT.withdraw()

# Ask user to select an image file.
FILE_SELECTED = filedialog.askopenfilename(title='Select Image')

# Query imghdr and print result.
print(imghdr.what(FILE_SELECTED))

# If the file format is unknown, (or not an image), returns NONE,
# otherwise returns file type by inspecting the header of the file,
# which is more reliable then taking the word of the files extension

Don’t forget to check out my other snippets, Snippets #1, #2, #3, #4, #5, #6, #7, #8, and #9

You can get all my source code snippets and projects from my Dropbox folder.

Using Python V3.6.5 on Windows 7 64bit

 

 

 

I have also started another free blog here of my personal memoirs (as if I don’t have enough to do already, LOL), if you want a peek, My Memoirs.

Advertisements


from Python Coder
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...