Python 標準ライブラリー
In [ ]:
import os
print(os.getcwd()) # Return the current working directory
os.chdir('C:/Users/904PP4148/Documents') # Change current working directory
print(os.getcwd())
os.system('mkdir today') # Run the command mkdir in the system shell
dir(os)
help(os)
In [ ]:
import shutil
shutil.copyfile('fileA', 'fileB')
shutil.move('/build/executables', 'installdir')
In [ ]:
import glob
glob.glob('*.py')
In [ ]:
import sys
print(sys.argv)
In [ ]:
sys.stderr.write('Warning, log file not found starting a new one\n')
In [31]:
import re
rst = re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')
print(rst)
rst = re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat')
print(rst)
In [32]:
rst = 'tea for too'.replace('too', 'two')
print(rst)
In [33]:
import math
print(math.cos(math.pi / 4))
print(math.log(1024, 2))
In [38]:
In [39]:
import statistics
data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5]
print(statistics.mean(data))
print(statistics.median(data))
print(statistics.variance(data))
In [43]:
from urllib.request import urlopen
with urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl') as response:
for line in response:
line = line.decode('utf-8') # Decoding the binary data to text.
if 'EST' in line or 'EDT' in line: # look for Eastern Time
print(line)
In [1]:
import urllib
proxy = urllib.request.ProxyHandler({'http': '127.0.0.1'})
opener = urllib.request.build_opener(proxy)
urllib.request.install_opener(opener)
In [ ]:
import smtplib
server = smtplib.SMTP('localhost')
server.sendmail('soothsayer@example.org', 'jcaesar@example.org',
"""To: jcaesar@example.org
From: soothsayer@example.org
Beware the Ides of March.
""")
server.quit()
In [49]:
from datetime import date
now = date.today()
print(now)
print(now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B."))
birthday = date(1964, 7, 31)
age = now - birthday
print(age.days)
In [53]:
import zlib
s = b'witch which has which witches wrist watch'
print(len(s))
t = zlib.compress(s)
print(t)
print(len(t))
print(zlib.decompress(t))
print(zlib.crc32(s))
In [54]:
from timeit import Timer
t1 = Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()
print(t1)
t2 = Timer('a,b = b,a', 'a=1; b=2').timeit()
print(t2)
In [56]:
def average(values):
"""Computes the arithmetic mean of a list of numbers.
>>> print(average([20, 30, 70]))
40.0
"""
return sum(values) / len(values)
import doctest
doctest.testmod() # automatically validate the embedded tests
Out[56]:
In [ ]:
import unittest
class TestStatisticalFunctions(unittest.TestCase):
def test_average(self):
self.assertEqual(average([20, 30, 70]), 40.0)
self.assertEqual(round(average([1, 5, 7]), 1), 4.3)
with self.assertRaises(ZeroDivisionError):
average([])
with self.assertRaises(TypeError):
average(20, 30, 70)
unittest.main() # Calling from the command line invokes all tests