python學習四:import模塊方法、可變參數、字典key判斷、版本信息獲取、列表解析、

1. import模塊方法

下面將具體介紹幾種常用情況:

(1)主程序與模塊程序在同一目錄下:
如下面程序結構:
`-- src
    |-- mod1.py
    `-- test1.py
    若在程序test1.py中導入模塊mod1, 則直接使用import mod1或from mod1 import *;
 
(2)主程序所在目錄是模塊所在目錄的父(或祖輩)目錄
如下面程序結構:
`-- src
    |-- mod1.py
    |-- mod2
    |   `-- mod2.py
    `-- test1.py
    若在程序test1.py中導入模塊mod2, 需要在mod2文件夾中建立空文件__init__.py文件(也可以在該文件中自定義輸出模塊接口); 然後使用 from mod2.mod2 import * 或import mod2.mod2.
 
(3)主程序導入上層目錄中模塊或其他目錄(平級)下的模塊
如下面程序結構:
`-- src
    |-- mod1.py
    |-- mod2
    |   `-- mod2.py
    |-- sub
    |   `-- test2.py
    `-- test1.py
    若在程序test2.py中導入模塊mod1和mod2。首先需要在mod2下建立__init__.py文件(同(2)),src下不必建立該文件。然後調用方式如下:
   下面程序執行方式均在程序文件所在目錄下執行,如test2.py是在cd sub;之後執行python test2.py
而test1.py是在cd src;之後執行python test1.py; 不保證在src目錄下執行python sub/test2.py成功。
   import sys
   sys.path.append("..")
   import mod1

   import mod2.mod2


2. 可變參數

def variation_args(*brands, **prices):
	print brands
	print prices

variation_args('apple', 'sumsung', 'nokia', 'htc', \
	apple = 4200, sumsung = 5000, nokia = 3500, htc = 3700)

輸出:

C:\Python27\python-code>python basic-1.py
['C:\\Python27\\python-code', 'C:\\windows\\system32\\python27.zip', 'C:\\Python
27\\DLLs', 'C:\\Python27\\lib', 'C:\\Python27\\lib\\plat-win', 'C:\\Python27\\li
b\\lib-tk', 'C:\\Python27', 'C:\\Python27\\lib\\site-packages']
Hello World
('apple', 'sumsung', 'nokia', 'htc')
{'nokia': 3500, 'sumsung': 5000, 'htc': 3700, 'apple': 4200}


3. 字典key判斷

(1) print dict.has_key('key') #True

(2) print  'key' in dict #True

(2) 效率高於(1)


4. 版本信息

>>> import sys
>>> sys.version
'2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)]'
>>>


5. 列表解析

example:
a = [x+2 for x in range(10)]
print a
輸出的結果:
[2, 3, 4, 5, 6, 7, 8, 9, 10, 11]


這個例子的執行過程:
python會在解釋器裏對range(10)進行迭代,依次把列表裏的內容取出來,賦值給最左邊的x,然後執行x+2的操作,
並且把執行好的結果保存在列表裏。等range(10)迭代完以後就新生成了一個列表,結果就是[2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
從上面可以看出,這也是建立python 列表的一個方法。


6. 文件操作

打開文件:

open("pathname","model","buffering"),後面的兩個參數可選,不填model,默認以只讀方式打開,buffering:0/false無緩衝   1/true 有緩衝

file("pathname",'model')

兩者的區別是用open函數,文件必須已經存在,否則會報找不到文件的錯誤;用file函數,文件存在則打開,不存在就創建。

f = file("test.txt", 'w')
f.write("1:insert some text in the test.txt file\n")
f.write("2: insert line two")
f.close()

o = open("test.txt")
print `o.read()`
o.close()


上例中若兩文件均不存在,則用open函數打開的就會報錯,用file函數打開的會自動創建再打開:


讀/寫文件:

f.read() 讀出所有內容;f.read(4)  讀取前4個字符       f.tell()  返回所讀取文件內字符的長度。

f = file("test.txt", 'w+')
f.write("Welcome: 1:insert line one\n")
f.write("2: insert line two")
f.close()

f=open("test.txt", 'r')
print "the top 8 char is %s" % f.read(8)
print "next read content is %s" % f.read()
print f.tell()


輸出:

the top 8 char is Welcome:
next read content is  1:insert line one
2: insert line two
46

f.seek(offset,whence)

offset:將光標移到offset定義的下標位置,在此處開始插入或讀取文件     whence:偏移量表示從什麼位置開始算offset,默認爲0-----表示光標從文件頭開始算起     1:表示相對於當前位置的移動,offset可以是負數     2:光標從文件結尾處開始算起

f = file("test.txt", 'w+')
f.write("Welcome: 1:insert line one\n")
f.write("2: insert line two")
f.close()
f = open("test.txt", 'r+')
print f.read()
f.seek(8)
f.write("****")
f.seek(0)
print f.read()
print "next 7 char is : '%s'" % f.read(7)
f.write('1234567')
print f.tell()


輸出:

Welcome: 1:insert line one
2: insert line two
Welcome:****nsert line one
2: insert line two
next 7 char is : ''
53

python常用的文件操作命令:


函數用來刪除一個文件:os.remove()

檢驗給出的路徑是否是一個文件:os.path.isfile()

檢驗給出的路徑是否是一個目錄:os.path.isdir()


返回一個路徑的目錄名和文件名:os.path.split()     eg os.path.split('/home/swaroop/byte/code/poem.txt') 結果:('/home/swaroop/byte/code', 'poem.txt')

分離擴展名:os.path.splitext()

獲取文件名:os.path.basename()

重命名:os.rename(old, new)

獲取文件屬性:os.stat(file)

修改文件權限與時間戳:os.chmod(file)

獲取文件大小:os.path.getsize(filename)

os.mknod("test.txt")        創建空文件
fp = open("test.txt",w)     直接打開一個文件,如果文件不存在則創建文件

關於open 模式:

w     以寫方式打開,
a     以追加模式打開 (從 EOF 開始, 必要時創建新文件)
r+     以讀寫模式打開
w+     以讀寫模式打開 (參見 w )
a+     以讀寫模式打開 (參見 a )
rb     以二進制讀模式打開
wb     以二進制寫模式打開 (參見 w )
ab     以二進制追加模式打開 (參見 a )
rb+    以二進制讀寫模式打開 (參見 r+ )
wb+    以二進制讀寫模式打開 (參見 w+ )
ab+    以二進制讀寫模式打開 (參見 a+ )

 

fp.read([size])                     #size爲讀取的長度,以byte爲單位

fp.readline([size])                 #讀一行,如果定義了size,有可能返回的只是一行的一部分

fp.readlines([size])                #把文件每一行作爲一個list的一個成員,並返回這個list。其實它的內部是通過循環調用readline()來實現的。如果提供size參數,size是表示讀取內容的總長,也就是說可能只讀到文件的一部分。

fp.write(str)                      #把str寫到文件中,write()並不會在str後加上一個換行符

fp.writelines(seq)            #把seq的內容全部寫到文件中(多行一次性寫入)。這個函數也只是忠實地寫入,不會在每行後面加上任何東西。

fp.close()                        #關閉文件。python會在一個文件不用後自動關閉文件,不過這一功能沒有保證,最好還是養成自己關閉的習慣。  如果一個文件在關閉後還對其進行操作會產生ValueError

fp.flush()                                      #把緩衝區的內容寫入硬盤

fp.fileno()                                      #返回一個長整型的”文件標籤“

fp.isatty()                                      #文件是否是一個終端設備文件(unix系統中的)

fp.tell()                                         #返回文件操作標記的當前位置,以文件的開頭爲原點

fp.next()                                       #返回下一行,並將文件操作標記位移到下一行。把一個file用於for … in file這樣的語句時,就是調用next()函數來實現遍歷的。

fp.seek(offset[,whence])              #將文件打操作標記移到offset的位置。這個offset一般是相對於文件的開頭來計算的,一般爲正數。但如果提供了whence參數就不一定了,whence可以爲0表示從頭開始計算,1表示以當前位置爲原點計算。2表示以文件末尾爲原點進行計算。需要注意,如果文件以a或a+的模式打開,每次進行寫操作時,文件操作標記會自動返回到文件末尾。

fp.truncate([size])                       #把文件裁成規定的大小,默認的是裁到當前文件操作標記的位置。如果size比文件的大小還要大,依據系統的不同可能是不改變文件,也可能是用0把文件補到相應的大小,也可能是以一些隨機的內容加上去。

存儲器:

#!/usr/bin/python
# Filename: pickling.py

import cPickle as p
#import pickle as p

shoplistfile = 'shoplist.data'
# the name of the file where we will store the object

shoplist = ['apple', 'mango', 'carrot']

# Write to the file
f = file(shoplistfile, 'w')
p.dump(shoplist, f) # dump the object to a file
f.close()

del shoplist # remove the shoplist

# Read back from the storage
f = file(shoplistfile)
storedlist = p.load(f)
print storedlist



發佈了30 篇原創文章 · 獲贊 1 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章