python

Reading Files

python

After you have opened a file you can read from it with the read() method. i[akraker@localhost:~]$ echo 'Hello, world!' > hello.txt i[akraker@localhost:~]$ cat hello.txt Hello, world! i[akraker@localhost:~]$ python Python 3.9.7 (default, Aug 30 2021, 00:00:00) [GCC 11.2.1 20210728 (Red Hat 11.2.1-1)] on linux Type "help", "copyright", "credits" or "license" for more information. i>>> helloFile = open('/home/akraker/hello.txt') i>>> helloContent = helloFile.read() i>>> helloContent 'Hello, world!\n' The read() method just get’s one long string from the file. ...

Reference

python

When a variable stores something (integer, string, etc) it’s actually storing a reference to the memory location where that thing is stored. For mutable data types, lists for example, this can have interesting consequences. You can copy a reference to some variable, change the data within the actual data and it will be changed in both places. >>> spam = [0, 1, 2, 3, 4, 5] >>> cheese = spam # The reference is being copied, not the list. ...

Regular Expressions in Python

python

>>> import re >>> phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d') >>> mo = phoneNumRegex.search('My number is 415-555-4242.') >>> print('Phone number found: ' + mo.group()) Phone number found: 415-555-4242 Import regex module with import re Create Regex object with the re.compile() function Pass the string you want to search into the Regex object’s search() method Call the Match object’s group() method to return the string of matched text Basic Regular Expression Syntax # Specifier Meaning - (This matches …) ? ...

remove()

python

The remove() method removes an item from the list by it’s value. >>> spam = ['cat', 'bat', 'rat', 'elephant'] >>> spam.remove('bat') >>> spam ['cat', 'rat', 'elephant'] If the item doesn’t exist it throws an error. If the item appears multiple times only the first occurrence is removed. See also # del Statement

Return Statement

python

A return statement defines a return value that returns a value when the function completes. A return statement consists of the following: The return keyword The value or expression that the function should return A return statement can be an expression. The value that’s returned is whatever the expression evaluates to.

reverse()

python

You can reverse the order of a list with the reverse() method. >>> spam = ['cat', 'dog', 'moose'] >>> spam.reverse() >>> spam ['moose', 'dog', 'cat']

Saving Variables

python

Variables can be saved or made to persist after the program has closed with the shelve module. i>>> import shelve i>>> shelfFile = shelve.open('mydata') i>>> cats = ['Zophie', 'Pooka', 'Simon'] i>>> shelfFile['cats'] = cats i>>> shelfFile.close() i>>> shelfFile = shelve.open('mydata') i>>> type(shelfFile) <class 'shelve.DbfilenameShelf'> i>>> shelfFile['cats'] ['Zophie', 'Pooka', 'Simon'] i>>> shelfFile.close() Shelf files are like dictionaries and use keys() and values() to return keys and values. i>>> shelfFile = shelve.open('mydata') i>>> list(shelfFile. ...

Saving Variables With pprint.pformat() Function

python

You can use pprint.pformat() to return a string that can be stored in a .py file and will be syntactically correct. i>>> import pprint i>>> cats = [{'name': 'Zophie', 'desc': 'chubby'}, {'name': 'Pooka', 'desc': 'fluffy'}] i>>> pprint.pformat(cats) "[{'desc': 'chubby', 'name': 'Zophie'}, {'desc': 'fluffy', 'name': 'Pooka'}]" i>>> fileObj = open('myCats.py', 'w') i>>> fileObj.write('cats = ' + pprint.pformat(cats) + '\n') 83 i>>> fileObj.close() i>>> import myCats i>>> myCats.cats [{'desc': 'chubby', 'name': 'Zophie'}, {'desc': 'fluffy', 'name': 'Pooka'}] i>>> myCats. ...

setdefault()

python

Using the setdefault() method you can check if a key exists and if it doesn’t set it to a default value. @>>> spam = {'name': 'Pooka', 'age': 5} @>>> spam.setdefault('color', 'black') 'black' @>>> spam {'name': 'Pooka', 'age': 5, 'color': 'black'} @>>> spam.setdefault('color', 'white') 'black' @>>> spam {'name': 'Pooka', 'age': 5, 'color': 'black'} Note, can’t set color after it has already been set.

shutile Module

python

The shutil stands for shell utilities. This allows us to manipulate files. Copying files and folders # shutil.copy() - Copy individual files. shutil.copytree() - Copy whole folders recursively. i>>> import shutil, os i>>> from pathlib import Path i>>> p = Path.home() i>>> shutil.copy(p / 'python' / 'bacon.txt', p / 'python/python.bak/') '/home/akraker/python/python.bak/bacon.txt' i>>> shutil.copy(p / 'python' / 'bacon.txt', p / 'python/python.bak/bacon2.txt') PosixPath('/home/akraker/python/python.bak/bacon2.txt') Moving and renaming files and folders #