Python3 tutorial day3

Modulers

A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended. Within a module, the module’s name (as a string) is available as the value of the global variable __name__

 

For instance, use your favorite text editor to create a file called fibo.py in the current directory with the following contents:

# Fibonacci numbers module

def fib(n):    # write Fibonacci series up to n
    a, b = 0, 1
    while b < n:
        print(b, end=' ')
        a, b = b, a+b
    print()

def fib2(n): # return Fibonacci series up to n
    result = []
    a, b = 0, 1
    while b < n:
        result.append(b)
        a, b = b, a+b
    return result

import fibo

fibo.fib(1000)
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
>>> fibo.__name__
'fibo'
>>> fib = fibo.fib
>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377
>>>

import变形,导入module里的方法

from fibo import fib, fib2
>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377

 

>>> from fibo import *

 

把module 当脚本用

在fibo.py文件下面加上如下代码

if __name__ == "__main__":
    import sys
    fib(int(sys.argv[1]))

python3 fibo.py 50
1 1 2 3 5 8 13 21 34

 

 

module 的搜索路径

首先搜索python的内置module;如果找不到搜索sys.path

sys.path由如下路径构成

.当前目录;

.PYTHONPATH

.安装的默认依赖

 

内置dir()函数

import fibo,sys
>>> dir(fibo)
['__builtins__', '__cached__', '__doc__', '__file__', '__name__', '__package__', 'fib', 'fib2', 'sys']
>>>

 

 

packages

Packages are a way of structuring Python’s module namespace by using “dotted module names”. 

 

import *

__init__.py 里定义一个__all__

__all__ = ["echo", "surround", "reverse"]

当用 from sound.effects import *是 导入的是上面三个module


>>> '12'.zfill(5)
'00012'
>>> '-3.14'.zfill(7)
'-003.14'
>>> print('We are the {} who say "{}!"'.format('knights', 'Ni'))
We are the knights who say "Ni!"
>>> print('{0} and {1}'.format('spam', 'eggs'))
spam and eggs
>>> print('{1} and {0}'.format('spam', 'eggs'))
eggs and spam

 

str.format() use keyword

 

print('This {food} is {adjective}.'.format(
...       food='spam', adjective='absolutely horrible'))
This spam is absolutely horrible.
 

'!a' (apply ascii()), '!s' (apply str()) and '!r' (apply repr()) can be used to convert the value before it is formatted:

>>>
>>> import math
>>> print('The value of PI is approximately {}.'.format(math.pi))
The value of PI is approximately 3.14159265359.
>>> print('The value of PI is approximately {!r}.'.format(math.pi))
The value of PI is approximately 3.141592653589793.


table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; '
...       'Dcab: {0[Dcab]:d}'.format(table))
Jack: 4098; Sjoerd: 4127; Dcab: 8637678


table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table))
Jack: 4098; Sjoerd: 4127; Dcab: 8637678
Old style
print('The value of PI is approximately %5.3f.' % math.pi)
The value of PI is approximately 3.142.

 Reading and Writing Files

open(filename, mode)

f = open('workfile', 'w')

第一个参数文件名,第二个参数是模式,表名文件以何种方式使用,默认是‘r’

‘r’ read

'w' write

'a' append

'r+' read & write

‘b’ byte

 

Read

read(),readline()

reading lines from file

for line in file:

   print(line)

 

Write

>>> f = open('workfile', 'rb+')
>>> f.write(b'0123456789abcdef')
16
>>> f.seek(5)
5
>>> f.read(1)
b'5'
>>> f.seek(-3, 2)
13
>>> f.read(1)
b'd'
>>> f.tell()
14
>>> f.read(1)
b'e'
>>> f.tell()
15
>>> f.closed
False
>>> f.close()
>>> f.closed
True
>>> with open('workfile', 'r') as f:
... read_data = f.read()
...
>>> read_data
'0123456789abcdef'
>>> f.closed
True

 

 

Json

>>> import json
>>> json.dumps([1, 'simple', 'list'])
'[1, "simple", "list"]'
>>> f = open('workfile','a+')
>>> x = [1, "simple", "list"]
>>> json.dump(x, f)
>>> f.close()
>>> f = open('workfile','r')
>>> x = json.load(f)
>>> x
[1, 'simple', 'list']

https://docs.python.org/3/library/json.html#module-json

 

posted on 2014-10-23 11:33  ukouryou  阅读(163)  评论(0编辑  收藏  举报

导航