Python Linux Academy

Lecture: Getting Started With Python 3

use the version 3 , the version 2.7 is installed in all the linux mac osx machine but it is convenient use python 3

sudo apt-get install python3

with the interactive shell you don't need to use print

first use of the console

giuseppe@giuseppe-Latitude-E7250 ~> python3
Python 3.4.0 (default, Apr 11 2014, 13:05:11) 
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> message = "hell"
>>> message
'hell'
>>> message = "hello world"
>>> message
'hello world'
>>> message[0:5]
'hello'
>>> message[:5]
'hello'
>>> message[:5] + " " + message
'hello hello world'

first script print the parameter

import sys
#print(sys.version) 
#single line comment
message = "Hello World"
print (message)
print (sys.argv[0])
print ("hi, " + sys.argv[1])

''' 
this is a multiline COMMENT
seriosly
'''

Basic File System Functions In Python

import os
# print the current working directory
print os.getcwd()
# list dir
print os.listdir("/home/giuseppe")
print os.mkdir("/home/giuseppe/test345")
os.chdir("/home/giuseppe/Documents")
print os.listdir(".")

scrape a directory

os.chdir("/home/giuseppe/Downloads/lastpassplugin")
for dirpath, dirnames, filenames in os.walk(os.getcwd(), topdown="true"):
     for filename in filenames:
          print(dirpath, filename)

operations with file

file = open("/home/giuseppe/pytest.txt","w")
print (file)

file.write("this is the test")
file.close()
file = None
file = open("/home/giuseppe/pytest.txt","r")
print (file.read())

if os.path.exists("/home/giuseppe/pytest.txt"):
    print ("found it")
else:
    print ("nope, didn't find it")

dir = "/home/giuseppe/pytest.txt"
if os.path.isfile(dir):
    print("it is a file")

if os.path.isdir("/home/giuseppe"):
    print ("it is a directory")    

import shutil
shutil.copy(dir, "/home/giuseppe/test3.txt")

os.rename("/home/giuseppe/test3.txt", "/home/giuseppe/test4.txt")
print (os.listdir("/home/giuseppe"))
os.remove("/home/giuseppe/test4.txt")

#the directory must be emtpy
os.removedirs("/home/giuseppe/test")

Lecture: Writing A Zip Archiving Script

import zipfile
import sys
import os
import logging
from symbol import except_clause

# setup a debug level
logging.basicConfig(filename='file_ex.log',level = logging.DEBUG)

logging.info("checking to see if the backup.zip exist")

if os.path.exists("backup.zip"):
    logging.info("it exist")
    try: 
        zip_file = zipfile.ZipFile('backup.zip','a')
    except:
        err = sys.exc_info()
        logging.error("unable to open backup.zip in appen mode")
        logging.error("error num: " + str(err[1].args[0]))
        logging.error("error msg: " + err[1].args[1])
        sys.exit()
else:
    logging.info("creating backup.zip")
    try:
        zip_file = zipfile.ZipFile("backup.zip", "w")
    except:
        err = sys.exc_info()
        logging.error("unable to create backup.zip")
        logging.error("error num: " + str(err[1].args[0]))
        logging.error("error msg: " + err[1].args[1])
        sys.exit()

logging.info("adding test.txt to backup.zip")

try:
    zip_file.write("test.txt", "test", zipfile.ZIP_DEFLATED)
except:
    err = sys.exc_info()
    logging.error("unable to open backup.zip in append mode")
    logging.error("error num: " + str(err[1].args[0]))
    logging.error("error msg: " + err[1].args[1])

Lecture: Sequence Data Type

List

create and appen value

giuseppe@giuseppe-Latitude-E7250 ~> python3
Python 3.4.0 (default, Apr 11 2014, 13:05:11) 
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> my_list = ["ship", "boat", "plane"]
>>> my_list
['ship', 'boat', 'plane']
>>> my_list.append("car")
>>> my_list
['ship', 'boat', 'plane', 'car']

remove last value pop

>>> my_list.pop()
'car'
>>> my_list
['ship', 'boat', 'plane']

insert in the second position

>>> my_list.insert(1,"car")
>>> my_list
['ship', 'car', 'boat', 'plane']

print only a slice of list from second position (1) to third position (2) , the forth position (4) is not included

>>> my_list[1:3]
['car', 'boat']

check if a value is in the list, revert a list

>>> if "ship" in my_list:
...     print ("True")
... 
True
>>> my_list.reverse()
>>> my_list
['plane', 'boat', 'car', 'ship']
>>>

Tuple

You can't change after that you configure but you can concatenate one to another

>>> my_tuple = ("car","boat","ship")
>>> my_tuple
('car', 'boat', 'ship')
>>> my_new_tuple = ("plane", "jetsky")
>>> my_really_new_tuple = my_tuple + my_new_tuple
>>> my_really_new_tuple
('car', 'boat', 'ship', 'plane', 'jetsky')
>>> my_tuple
('car', 'boat', 'ship')

Ranges

>>> my_range = list(range(0,22,2))
>>> my_range
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

Lecture: Strings and Dictionaries

Strings

string are considered sequences but we can't do all the operation saw before but only a subpart
we can't do a reverse for example

>>> my_string = 'The red hat'
>>> my_string[1:4]
'he '
>>> my_string[1:]
'he red hat'
>>> my_string.reverse()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'reverse'
>>> for i in my_string:
...     print(i)
... 
T
h
e

r
e
d

h
a
t

split a string , the default value is the space

>>> my_string = 'The red hat'
>>> my_string
'The red hat'
>>> my_list = my_string.split()
>>> my_list
['The', 'red', 'hat']
>>> my_string.join(my_list)
'TheThe red hatredThe red hathat'

remove space

>>> my_new_string = '  TheRedHAt'
>>> my_new_string.strip()
'TheRedHAt'

Dictionaries

key and values

>>> my_dict = {'ship':'RX44', 'car':'Fiesta','plane':'747'}
>>> my_dict.keys()
dict_keys(['plane', 'ship', 'car'])
>>> my_dict.values()
dict_values(['747', 'RX44', 'Fiesta'])
>>> len(my_dict)
3
>>> my_dict['train'] = 'BG108'
>>> my_dict
{'plane': '747', 'train': 'BG108', 'ship': 'RX44', 'car': 'Fiesta'}
>>> my_dict['car'] = 'Escort'
>>> my_dict['car']
'Escort'
>>> for k,v in my_dict.items():
...     print(k + ":" + v)
... 
plane:747
train:BG108
ship:RX44
car:Escort
>>>
Salvo diversa indicazione, il contenuto di questa pagina è sotto licenza Creative Commons Attribution-ShareAlike 3.0 License