1. 程式人生 > >python3 常用模組(時間、os路徑及檔案操作、字串比較,檔案內容比較等模組)

python3 常用模組(時間、os路徑及檔案操作、字串比較,檔案內容比較等模組)

python裡面有很多模組,以實現各種功能,學習python,我個人認為最重要的是熟練掌握模組的功能,靈活應用,首先就要掌握基礎模組。

本文的主要模組包括:時間的模組(time,datetime和calendar)os模組(路徑操作模組os.path,讀寫檔案模組open(),多個檔案讀寫處理模組fileinput,建立當前檔案模組tempfile等),檔案本身的資訊訪問os.stat(path)和字串的讀取textwrap模組、字串比較模組difflib和檔案比較模組filecmp。

1. 時間的模組(time,datetime和calendar)

    這三個模組就是python對時間的處理,包括時間的訪問,時差計算,檢視日曆,等等。常用的操作如下:

<span style="font-size:12px;">import time
import datetime
import calendar

now  = datetime.datetime.now()
print(now.strftime('%Y-%m-%d %H:%M:%S')) #輸出日期、時間的格式(字串變時間格式)

time_strA = '2014-07-29 01:15:00'
time_strB ='2014-08-29 01:15:00'
#  .strptime()函式 為時間格式轉變為字串個格式
day = datetime.datetime.strptime(time_strA, '%Y-%m-%d %H:%M:%S')
day2 = datetime.datetime.strptime(time_strB, '%Y-%m-%d %H:%M:%S')
sub_day = day2 - day
print('{0}和{1}相差{2}天'.format(time_strA, time_strB, str(sub_day.days)))
#時間延遲 用datetime.timedelta()函式 今後一個星期零三天
N=3
M = 1
N_date = datetime.timedelta(weeks = 1,days = N)
day = now + N_date
print(day.strftime('%Y-%m-%d %H:%M:%S'))</span>
<pre name="code" class="python"><span style="font-size:12px;">
</span>
<span style="font-size:12px;">#日曆的常見函式
calendar.month(year, month)
calendar.calendar(year)
calendar.isleap(year)#判斷是否是閏年
calendar.monthrange(year, month)#返回指定年的月的日期
calendar.monthcalendar(year, month)#指定年月的周</span>
2. os模組

     首先,這個模組為作業系統的函式模組,涵蓋其他的許多模組,如:路徑操作模組os.path,讀寫檔案模組open(),多個檔案讀寫處理模組fileinput,建立當前檔案模組tempfile等。

A . os和os.path模組常見運用

<span style="font-size:12px;">import os
pa = os.getcwd()#獲取當前工作目錄
print(os.listdir(pa))#路徑pa中的檔案及資料夾展開
path = r'C:\test.html'
print(os.path.abspath(path)) #絕對路徑
print(os.path.dirname(path)) #路徑名的資料夾名稱
print(os.path.getatime(path)) #最後一次訪問時間,還有其他的函式,如最後一次修改時間等
print(os.path.isfile(path))#判斷是否為檔案,還有路徑分割等os.path.split(path)、os.<tt class="descclassname">path.</tt><tt class="descname">splitext</tt><big>(</big><em>path</em><big>)</big>及合併os.path.jion()
print(os.path.exists(path))#判斷路徑是否存在
print(os.path.isdir(path)) #是否是資料夾
print(os.path.getsize(path))#檔案大小</span>

B. 檔案操作open()、fileinput和tempfile模組

   最常用的就是單個檔案的讀寫操作,包括二進位制的讀寫,open()如下:

<span style="font-size:12px;">import os
path = r'C:\test.html'

fp = open(path,'w+')#寫操作開啟
#fp = open(path,'w+b') 二進位制寫操作
content = 'adf'
fp.write(content)
fp.flush()
fp.close()
fp = open(path,'r+')#讀
print('讀取檔案:{0}所有內容:{1}'.format(path,fp.readlines())) </span>
fileinput模組對多個檔案處理,則路徑存文tuple型別,如下:
<span style="font-size:12px;">import os
import fileinput

paths = (r'C:\test.html',r'C:\test.txt')

fp = fileinput.input(paths) #載入
lines = ''
names = []
for line in fp:
    lines +=line  #兩個檔案所有內容一起讀取到lines中
    name = fileinput.filename()#檔名
    names.append(name)
print(lines)
</span>
tempfile在快取中建立零時檔案(夾),其他程式不能共享該快取中的零時檔案,因為它並沒有引用檔案系統表。而用TemporaryFile這個函式建立的臨時檔案,關閉檔案後會自動刪除。
import os
import tempfile

path = r'C:\test.%s.txt'%os.getpid()

fp = open(path,'w+b') #載入
content = b'ccc'  #要變為二進位制才能寫
fp.write(content)
fp.close()
os.remove(path) #手動刪除零時檔案
#用TemporaryFile來建立,關閉檔案時自動刪除
fil = tempfile.TemporaryFile()
fil.write(b'ddd')
fil.seek(0)
print(fil.read())
fil.close() #關閉時,零時檔案自動刪除
3. 檔案本身的資訊訪問os.stat(path)和字串的讀取textwrap模組、字串比較模組difflib和檔案比較模組filecmp

os.stat(path)是對檔案本身資訊的訪問,有是個屬性,如下:

import os
import stat
st_mode    -- protection
st_ino     -- inode number(索引號)
st_nlink   -- number of hard links(硬連結號)
st_uid     -- user id of owner(使用者id)
st_gid     -- group id of owner (組id)
st_size    -- size of file,in bytes (大小)
st_atime   -- time of most recent access expressed in seconds (訪問時間)
st_mtime   -- time of most recent content modificatin expressed in seconds (修改時間)
st_ctime
#訪問格式為
os.stat(path).st_size 或 os.stat(path)[stat.ST_SIZE]
這兩種表示方法是一樣的。
字串讀取textwrap,包括wrap(),fill(),dedent()等方法
import textwrap

test_content = '''dakjhdklghkjaghsaghskghskfh'''
print(textwrap.wrap(test_comntent,5))#將字串test_content按長度5切片為元組
print(textwrap.fill(test_conten,10))#將字串test_content按每行10個字元拆開並且逐行顯示
print(textwrap.dedent(test_conten))#不縮排顯示,即換行符並不換行,此行繼續顯示
檔案內容、字串比較模組difflib,比較後可以用模組HtmlDiff模組來顯示在檔案.html中(表格):
import difflib
import os
from difflib import HtmlDiff
if os.path.exists('C:\\test.html'):
    with open('C:\\test.html','w+') as fp:
        test = HtmlDiff.make_file(HtmlDiff(), 'hello world!', 'hElLO Wor2d!')
        fp.write(test)
        print('生成檔案成功!')
        fp.close()
#或者如下
test = difflib.Differ().compare('hello world', 'HeLLO,wOrlD!')
print('橫向展示:')
print(''.join(list(test)))

還有一個比較檔案內容的filecmp模組,轉載來源:http://scm002.iteye.com/blog/1662812

filecmp模組用於比較檔案及資料夾的內容,它是一個輕量級的工具,使用非常簡單。python標準庫還提供了difflib模組用於比較檔案的內容。關於difflib模組,且聽下回分解。

    filecmp定義了兩個函式,用於方便地比較檔案與資料夾:

filecmp.cmp(f1, f2[, shallow]):

    比較兩個檔案的內容是否匹配。引數f1, f2指定要比較的檔案的路徑。可選引數shallow指定比較檔案時是否需要考慮檔案本身的屬性(通過os.stat函式可以獲得檔案屬性)。如果檔案內容匹配,函式返回True,否則返回False。

filecmp.cmpfiles(dir1, dir2, common[, shallow]):

    比較兩個資料夾內指定檔案是否相等。引數dir1, dir2指定要比較的資料夾,引數common指定要比較的檔名列表。函式返回包含3個list元素的元組,分別表示匹配、不匹配以及錯誤的檔案列表。錯誤的檔案指的是不存在的檔案,或檔案被瑣定不可讀,或沒許可權讀檔案,或者由於其他原因訪問不了該檔案。

    filecmp模組中定義了一個dircmp類,用於比較資料夾,通過該類比較兩個資料夾,可以獲取一些詳細的比較結果(如只在A資料夾存在的檔案列表),並支援子資料夾的遞迴比較。

dircmp提供了三個方法用於報告比較的結果

  • report():只比較指定資料夾中的內容(檔案與資料夾)
  • report_partial_closure():比較資料夾及第一級子資料夾的內容
  • report_full_closure():遞迴比較所有的資料夾的內容

例子:在資料夾"1"中含有檔案"1.txt", 在資料夾"2"中含有檔案"1.txt"和"2.txt",其兩個資料夾下面的檔案"1.txt"內容一樣,

>>>import filecmp
>>>x = filecmp.dircmp("1", "2")
>>>x.report()
>>>
diff 1 2
Only in 2 : ['2.txt']
Identical files : ['1.txt']

如果兩個資料夾下面的檔案"1.txt"內容不相同那麼結果如下:

>>>import filecmp
>>>x = filecmp.dircmp("1", "2")
>>>x.report()
>>>
diff 1 2
Only in 2 : ['2.txt']
Differing files : ['1.txt'] 

dircmp還提供了下面這些屬性用於獲取比較的詳細結果

  • left_list:左邊資料夾中的檔案與資料夾列表;
  • right_list:右邊資料夾中的檔案與資料夾列表;
  • common:兩邊資料夾中都存在的檔案或資料夾;
  • left_only:只在左邊資料夾中存在的檔案或資料夾;
  • right_only:只在右邊資料夾中存在的檔案或資料夾;
  • common_dirs:兩邊資料夾都存在的子資料夾;
  • common_files:兩邊資料夾都存在的子檔案;
  • common_funny:兩邊資料夾都存在的子資料夾;
  • same_files:匹配的檔案;
  • diff_files:不匹配的檔案;
  • funny_files:兩邊資料夾中都存在,但無法比較的檔案;
  • subdirs:我沒看明白這個屬性的意思,python手冊中的解釋如下:A dictionary mapping names in common_dirs to dircmp objects

    簡單就是美!我只要檔案比較的結果,不想去關心檔案是如何是比較的,hey,就用python吧~~