目錄操作
1、得到目前工作目錄,即目前Python腳本工作的目錄路徑: os.getcwd()
>>> import os
>>> os.getcwd()
'/home/jack'
2、傳回指定目錄下的所有檔案和目錄名:os.listdir()
>>> os.listdir('/home/jack')
['.profile', '.bashrc', 'test', '.bash_logout']
3、函數用來删除一個檔案:os.remove()
#建立檔案 >>> os.mknod("t1.txt")
#顯示目前目錄下的所有檔案
['.profile', '.bashrc', 't1.txt', 'test', '.bash_logout']
#删除檔案
>>> os.remove("t1.txt")
4、删除多個目錄:os.removedirs(r“c:\python”)
#建立多個目錄
>>> os.makedirs("t1/t2")
['.profile', '.bashrc', 't1', 'test', '.bash_logout']
>>> os.listdir('/home/jack/t1')
['t2']
#删除多個目錄
>>> os.removedirs(r"/home/jack/t1/t2")
os.listdir('/home/jack')
5、檢驗給出的路徑是否是一個檔案:os.path.isfile()
>>> os.path.isfile('.bashrc')
True
>>> os.path.isfile('.bashrc1')
False
6、檢驗給出的路徑是否是一個目錄:os.path.isdir()
>>> os.path.isdir('/home/jack/test')
>>> os.path.isdir('/home/jack/test1')
7、判斷是否是絕對路徑:os.path.isabs()
>>> os.path.isabs('/home/jack/test')
>>> os.path.isabs('test')
8、檢驗給出的路徑是否真地存:os.path.exists()
>>> os.path.exists('test')
>>> os.path.exists('test1')
9、傳回一個路徑的目錄名和檔案名:os.path.split()
>>> os.path.split('/home/jack/test')
('/home/jack', 'test')
10、分離擴充名:os.path.splitext()
>>> os.path.splitext('/home/jack/test')
('/home/jack/test', '')
11、擷取路徑名:os.path.dirname()
>>> os.path.dirname('/home/jack/')
12、擷取檔案名:os.path.basename()
>>> os.mknod('a.txt')
>>> os.path.basename('/home/jack/a.txt')
'a.txt'
13、運作shell指令: os.system()
>>> os.system('ls -a')
. .. a.txt .bash_logout .bashrc .profile test
14、讀取和設定環境變量:os.getenv() 與os.putenv()
getenv(key, default=None)
Get an environment variable, return None if it doesn't exist.
The optional second argument can specify an alternate default.
15、重命名:os.rename(old, new)
>>> os.listdir("/home/jack")
['.profile', 'a.txt', '.bashrc', '.bash_history', '.ipython', 'test', '.bash_logout']
>>> os.rename('a.txt','b.txt')
['.profile', '.bashrc', '.bash_history', '.ipython', 'b.txt', 'test', '.bash_logout']
16、建立多級目錄:os.makedirs()
>>> os.makedirs('t1/t2')
['.profile', '.bashrc', '.bash_history', '.ipython', 't1', 'b.txt', 'test', '.bash_logout']
17、建立單個目錄:os.mkdir()
>>> os.mkdir('abc')
['.profile', 'abc', '.bashrc', '.bash_history', '.ipython', 't1', 'b.txt', 'test', '.bash_logout']
18、擷取檔案屬性:os.stat(file)
>>> os.stat('b.txt')
posix.stat_result(st_mode=33152, st_ino=927137, st_dev=64769, st_nlink=1, st_uid=1001, st_gid=1001, st_size=0, st_atime=1510235921, st_mtime=1510235921, st_ctime=1510277660)
19、修改檔案權限與時間戳:os.chmod(file)
參考部落格:http://blog.csdn.net/wirelessqa/article/details/7974477
20、終止目前程序:os.exit()
21、擷取檔案大小:os.path.getsize(filename)
>>> os.path.getsize('b.txt')
檔案操作
os.mknod("test.txt") #建立空檔案
fp = open("test.txt",w) #直接打開一個檔案,如果檔案不存在則建立檔案
r:以讀方式打開檔案,可讀取檔案資訊。
w:以寫方式打開檔案,可向檔案寫入資訊。如檔案存在,則清空該檔案,再寫入新内容;如果檔案不存在則建立
a:以追加模式打開檔案(即一打開檔案,檔案指針自動移到檔案末尾),如果檔案不存在則建立
r+:以讀寫方式打開檔案,可對檔案進行讀和寫操作。
w+:消除檔案内容,然後以讀寫方式打開檔案。
a+:以讀寫方式打開檔案,并把檔案指針移到檔案尾。
b:以二進制模式打開檔案,而不是以文本模式。該模式隻對Windows或Dos有效,類Unix的檔案是用二進制模式進行操作的。
檔案操作方法
常見檔案操作方法:
方法
f.close() 關閉檔案,記住用open()打開檔案後一定要記得關閉它,否則會占用系統的可打開檔案句柄數。
f.name() 擷取檔案名稱
f.next() 傳回下一行,并将檔案操作标記位移到下一行。把一個file用于for … in file這樣的語句時,就是調用next()函數來實作周遊的。
f.flush() 重新整理輸出緩存,把緩沖區的内容寫入硬碟
f.isatty() 如果檔案是一個終端裝置檔案(Linux系統中),則傳回True,否則傳回False。
f.read([size]) 讀出檔案,size為讀取的長度,以byte為機關
f.readline([size]) 讀出一行資訊,若定義了size,則讀出一行的一部分
f.readlines([size]) 讀出所有行,也就是讀出整個檔案的資訊。(把檔案每一行作為一個list的一個成員,并傳回這個list。其實它的内部是通過循環調用readline()來實作的。如果提供size參數,size是表示讀取内容的總長,也就是說可能隻讀到檔案的一部分)
f.seek(offset[,where])
把檔案指針移動到相對于where的offset位置。where為0表示檔案開始處,這是預設值;1表示目前位置;2表示檔案結尾。(注意:如果檔案以a或a+的模式打開,每次進行寫操作時,檔案操作标記會自動傳回到檔案末尾)
f.tell() 獲得檔案指針位置,标記目前位置,以檔案開頭為原點
f.truncate([size]) 把檔案裁成規定的大小,預設的是裁到目前檔案操作标記的位置。如果size比檔案的大小還要大,依據系統的不同可能是不改變檔案,也可能是用0把檔案補到相應的大小,也可能是以一些随機的内容加上去。
f.write(string) 把string字元串寫入檔案,write()不會在str後加上一個換行符。
f.writelines(list) 把list中的字元串一行一行地寫入檔案,是連續寫入檔案,沒有換行。
檔案操作模式舉例
w 模式,如果沒有檔案,會自動建立
1
2
3
4
5
6
<code>>>> os.listdir(</code><code>'/home/jack'</code><code>)</code>
<code>[</code><code>'.profile'</code><code>, </code><code>'abc'</code><code>, </code><code>'.bashrc'</code><code>, </code><code>'.bash_history'</code><code>, </code><code>'.ipython'</code><code>, </code><code>'t1'</code><code>, </code><code>'b.txt'</code><code>, </code><code>'test'</code><code>, </code><code>'.bash_logout'</code><code>]</code>
<code>>>> f1 </code><code>=</code> <code>open</code><code>(</code><code>'hello.txt'</code><code>,</code><code>'w'</code><code>)</code>
<code>>>> f1.write(</code><code>'hello world\n'</code><code>)</code>
<code>>>> f1.flush() </code><code>#重新整理輸出緩存,把緩沖區的内容寫入硬碟</code>
<code>>>> f1.close()</code>
r 模式 隻讀模式
<code>>>> f1 </code><code>=</code> <code>open</code><code>(</code><code>'hello.txt'</code><code>,</code><code>'r'</code><code>)</code>
<code>>>> </code><code>print</code><code>(f1.read())</code>
<code>hello world</code>
r+ 模式 以讀寫方式打開檔案,可對檔案進行讀和寫操作。會清空原檔案
<code>>>> f1 </code><code>=</code> <code>open</code><code>(</code><code>'hello.txt'</code><code>,</code><code>'r+'</code><code>)</code>
<code>>>> f1.write(</code><code>'hello2 world\n'</code><code>)</code>
<code>hello2 world</code>
w+ 模式 消除檔案内容,然後以讀寫方式打開檔案。
7
<code>>>> f1 </code><code>=</code> <code>open</code><code>(</code><code>'hello.txt'</code><code>,</code><code>'w+'</code><code>)</code>
<code>>>> f1.write(</code><code>'hello world ,hello world\n'</code><code>)</code>
<code>hello world ,hello world</code>
a 模式 以追加模式打開檔案(即一打開檔案,檔案指針自動移到檔案末尾)
如果檔案不存在則建立,原有的檔案内容保留
<code>>>> f1 </code><code>=</code> <code>open</code><code>(</code><code>'hello.txt'</code><code>,</code><code>'a'</code><code>)</code>
<code>>>> f1.write(</code><code>'h2 h2\n'</code><code>)</code>
<code>h2 h2</code>
a+ 模式 以讀寫方式打開檔案,并把檔案指針移到檔案尾。
8
<code>>>> f1 </code><code>=</code> <code>open</code><code>(</code><code>'hello.txt'</code><code>,</code><code>'a+'</code><code>)</code>
<code>>>> f1.write(</code><code>'h3 h3 h3\n'</code><code>)</code>
<code>h3 h3 h3</code>
b :模式一般用于二進制檔案的操作
檔案讀寫方法
read # 讀出所有檔案,size為讀取的長度,以byte為機關
readline #一行一行的讀取
readlines #讀出所有行,也就是讀出整個檔案的資訊。(把檔案每一行作為一個list的一個成員,并傳回這個list。其實它的内部是通過循環調用readline()來實作的。如果提供size參數,size是表示讀取内容的總長,也就是說可能隻讀到檔案的一部分)
本文轉自 水滴石川1 51CTO部落格,原文連結:http://blog.51cto.com/sdsca/1980534,如需轉載請自行聯系原作者