>>> import os
>>> os.getcwd() # Return the current working directory'C:\\Python35'>>> os.chdir('/server/accesslogs') # Change current working directory>>> os.system('mkdir today') # Run the command mkdir in the system shell0
应该用 import os 风格而非 from os import *。这样可以保证随操作系统不同而有所变化的 os.open() 不会覆盖内置函数 open()。
在使用一些像 os 这样的大型模块时内置的 dir() 和 help() 函数非常有用:
>>> import os
>>> dir(os)
<returns a list of all module functions>
>>> help(os)
<returns an extensive manual page created from the module's docstrings>
>>> sys.stderr.write('Warning, log file not found starting a new one\n')
Warning, logfilenot found starting anewone
大多脚本的直接终止都使用 sys.exit()。
10.5. 字符串正则匹配
re 模块为高级字符串处理提供了正则表达式工具。对于复杂的匹配和处理,正则表达式提供了简洁、优化的解决方案:
>>> import re
>>> re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')
['foot', 'fell', 'fastest']
>>> re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat')
'cat in the hat'
>>> from urllib.request import urlopen
>>> for line in urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'):
... 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)
<BR>Nov. 25, 09:43:32 PM EST
>>> 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()
>>> # dates are easily constructed and formatted>>> from datetime import date
>>> now = date.today()
>>> now
datetime.date(2003, 12, 2)
>>> now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")
'12-02-03. 02 Dec 2003 is a Tuesday on the 02 day of December.'>>> # dates support calendar arithmetic>>> birthday = date(1964, 7, 31)
>>> age = now - birthday
>>> age.days
14368
>>> import zlib
>>> s = b'witch which has which witches wrist watch'>>> len(s)
41>>> t = zlib.compress(s)
>>> len(t)
37>>> zlib.decompress(t)
b'witch which has which witches wrist watch'>>> zlib.crc32(s)
226805979
defaverage(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
import unittest
classTestStatisticalFunctions(unittest.TestCase):deftest_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