import math import cmath # Complex for cpx in [3j, 1.5 + 1j, -2 - 2j]: # Polar coordinate conversion plr = cmath.polar(cpx) print 'Complex:', cpx print 'Polar:', plr, '(in radians)' print 'Amplitude:', abs(cpx) print 'Angle:', math.degrees(plr[1]), '(grades)' import random import string # Choose a letter print random.choice(string.ascii_uppercase) # Choose a number from 1 to 10 print random.randrange(1, 11) # Choose a float from 0 to 1 print random.random() from decimal import Decimal t = 5. for i in range(50): t = t - 0.1 print 'Float:', t t = Decimal('5.') for i in range(50): t = t - Decimal('0.1') print 'Decimal:', t from fractions import Fraction # Three fractions f1 = Fraction('-2/3') f2 = Fraction(3, 4) f3 = Fraction('.25') print "Fraction('-2/3') =", f1 print "Fraction('3, 4') =", f2 print "Fraction('.25') =", f3 # Sum print f1, '+', f2, '=', f1 + f2 print f2, '+', f3, '=', f2 + f3 import sys # Create an object of type file temp = open('temp.txt', 'w') # Write output for i in range(20): temp.write('%03d\n' % i) temp.close() temp = open('temp.txt') # Write in terminal for x in temp: # writing in sys.stdout sends # text to standard output sys.stdout.write(x) temp.close() import sys import os.path fn = 'test.txt' if not os.path.exists(fn): print 'Try again...' sys.exit() # Numbering lines for i, s in enumerate(open(fn)): print i + 1, s, # Prints a list with all the lines from a file print open('temp.txt').readlines() import os.path import glob # Shows a list of file names # and their respective sizes for arq in sorted(glob.glob('*.py')): print arq, os.path.getsize(arq) import os text = 'Test' # creates a temporary file temp = os.tmpfile() # writes in the temp file temp.write(text) # Go back to the beginning the the file temp.seek(0) # Shows file content print temp.read() # Closes file temp.close() """ Writing text in a compressed file """ import zipfile text = """ ************************************** This text will be compressed and ... ... stored inside a zip file. *************************************** """ # Creates a new zip zip = zipfile.ZipFile('arq.zip', 'w', zipfile.ZIP_DEFLATED) # Writes a string in zip as if it were a file zip.writestr('text.txt', text) # closes the zip zip.close() """ Reading a compressed file """ import zipfile # Open the zip file for reading zip = zipfile.ZipFile('arq.zip') # Gets a list of compressed files arqs = zip.namelist() for arq in arqs: # Shows the file name print 'File:', arq # get file info zipinfo = zip.getinfo(arq) print 'Original size:', zipinfo.file_size print 'Compressed size:', zipinfo.compress_size # Shows file content print zip.read(arq) import csv # Data dt = (('temperatura', 15.0, 'C', '10:40', '2006-12-31'), ('peso', 42.5, 'kg', '10:45', '2006-12-31')) # A writing routine which receives one object of type file out = csv.writer(file('dt.csv', 'w')) # Writing the tuples in file out.writerows(dt) import csv # The reading routine receives a file object dt = csv.reader(file('dt.csv')) # For each record in file, prints for reg in dt: print reg import os import sys import platform def uid(): """ uid() -> returns the current user identification or None if not possible to identify """ # Ambient variables for each operating system us = {'Windows': 'USERNAME', 'Linux': 'USER'} u = us.get(platform.system()) return os.environ.get(u) print 'User:', uid() print 'plataform:', platform.platform() print 'Current dir:', os.path.abspath(os.curdir) exep, exef = os.path.split(sys.executable) print 'Executable:', exef print 'Executable dir:', exep import sys from subprocess import Popen, PIPE # ping cmd = 'ping -c 1 ' # No Windows if sys.platform == 'win32': cmd = 'ping -n 1 ' # Local just for testing host = '127.0.0.1' # Comunicates with another process # a pipe with the command stdout py = Popen(cmd + host, stdout=PIPE) # Shows command output print py.stdout.read() import time # localtime() Returns a date and local time in the form # of a structure called struct_time, which is a # collection with the items: year, month, day, hour, minute, # secund, day of the week, day of the year and e daylight saving time print time.localtime() # asctime() returns a date and hour with string, according to # operating system configuration print time.asctime() # time() returns system time in seconds ts1 = time.time() # gmtime() converts seconds to struct_time tt1 = time.gmtime(ts1) print ts1, '->', tt1 # Adding an hour tt2 = time.gmtime(ts1 + 3600.) # mktime() converts struct_time to seconds ts2 = time.mktime(tt2) print ts2, '->', tt2 # clock() returs time since the program started, in seconds print 'The program took', time.clock(), \ 'seconds up to now...' # Counting seconds... for i in xrange(5): # sleep() waits the number of seconds specified as parameter time.sleep(1) print i + 1, 'second(s)' import datetime # datetime() receives as parameter: # year, month, day, hour, minute, second and # returns an object of type datetime dt = datetime.datetime(2020, 12, 31, 23, 59, 59) # Objects date and time can be created from # a datetime object date = dt.date() hour = dt.time() # How many time to 12/31/2020 dd = dt - dt.today() print 'Date:', date print 'Hour:', hour print 'How many time to 12/31/2020:', dd import re # Compile the regular expression using compile() # the compiled regular expression is stored and # can be reused rex = re.compile('\w+') # Finds the occurrences according to the expression bands = 'Yes, Genesis & Camel' print bands, '->', rex.findall(bands) # Identify occurrences of Björk (and their variations) bjork = re.compile('[Bb]j[öo]rk') for m in ('Björk', 'björk', 'Biork', 'Bjork', 'bjork'): # match() finds occurrences at the beginning of the string # to find at any part of the string, use search() print m, '->', bool(bjork.match(m)) # Replacing text text = 'The next track is Stairway to Heaven' print text, '->', re. sub('[Ss]tairway [Tt]o [Hh]eaven', 'The Rover', text) # Splitting text bands = 'Tool, Porcupine Tree and NIN' print bands, '->', re.split(',?\s+and?\s+', bands)