python 檔案操作api

來源:互聯網
上載者:User
python中對檔案、檔案夾(檔案操作函數)的操作需要涉及到os模組和shutil模組。

得到當前工作目錄,即當前Python指令碼工作的目錄路徑: os.getcwd()
返回指定目錄下的所有檔案和目錄名:os.listdir()
函數用來刪除一個檔案:os.remove()
刪除多個目錄:os.removedirs(r“c:\python”)
檢驗給出的路徑是否是一個檔案:os.path.isfile()
檢驗給出的路徑是否是一個目錄:os.path.isdir()
判斷是否是絕對路徑:os.path.isabs()
檢驗給出的路徑是否真地存:os.path.exists()
返回一個路徑的目錄名和檔案名稱:os.path.split() eg os.path.split('/home/swaroop/byte/code/poem.txt') 結果:('/home/swaroop/byte/code', 'poem.txt')
分離副檔名:os.path.splitext()
擷取路徑名:os.path.dirname()
擷取檔案名稱:os.path.basename()
運行shell命令: os.system()
讀取和設定環境變數:os.getenv() 與os.putenv()
給出當前平台使用的行終止符:os.linesep Windows使用'\r\n',Linux使用'\n'而Mac使用'\r'
指示你正在使用的平台:os.name 對於Windows,它是'nt',而對於Linux/Unix使用者,它是'posix'
重新命名:os.rename(old, new)
建立多級目錄:os.makedirs(r“c:\python\test”)
建立單個目錄:os.mkdir(“test”)
擷取檔案屬性:os.stat(file)
修改檔案許可權與時間戳記:os.chmod(file)
終止當前進程:os.exit()
擷取檔案大小: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把檔案補到相應的大小,也可能是以一些隨機的內容加上去。

目錄操作:
os.mkdir("file") 建立目錄
複製檔案:
shutil.copyfile("oldfile","newfile") oldfile和newfile都只能是檔案
shutil.copy("oldfile","newfile") oldfile只能是檔案夾,newfile可以是檔案,也可以是目標目錄
複製檔案夾:
shutil.copytree("olddir","newdir") olddir和newdir都只能是目錄,且newdir必須不存在
重新命名檔案(目錄)
os.rename("oldname","newname") 檔案或目錄都是使用這條命令
移動檔案(目錄)
shutil.move("oldpos","newpos")
刪除檔案
os.remove("file")
刪除目錄
os.rmdir("dir")只能刪除空目錄
shutil.rmtree("dir") 空目錄、有內容的目錄都可以刪
轉換目錄
os.chdir("path") 換路徑

相關例子

1 將檔案夾下所有圖片名稱加上'_fc'

python代碼:

# -*- coding:utf-8 -*-import reimport osimport time#str.split(string)分割字串#'串連符'.join(list) 將列表組成字串def change_name(path):  global i  if not os.path.isdir(path) and not os.path.isfile(path):    return False  if os.path.isfile(path):    file_path = os.path.split(path) #分割出目錄與檔案    lists = file_path[1].split('.') #分割出檔案與副檔名    file_ext = lists[-1] #取出尾碼名(列表切片操作)    img_ext = ['bmp','jpeg','gif','psd','png','jpg']    if file_ext in img_ext:      os.rename(path,file_path[0]+'/'+lists[0]+'_fc.'+file_ext)      i+=1 #注意這裡的i是一個陷阱    #或者    #img_ext = 'bmp|jpeg|gif|psd|png|jpg'    #if file_ext in img_ext:    #  print('ok---'+file_ext)  elif os.path.isdir(path):    for x in os.listdir(path):      change_name(os.path.join(path,x)) #os.path.join()在路徑處理上很有用img_dir = 'D:\\xx\\xx\\images'img_dir = img_dir.replace('\\','/')start = time.time()i = 0change_name(img_dir)c = time.time() - startprint('程式運行耗時:%0.2f'%(c))print('總共處理了 %s 張圖片'%(i))

輸出結果:

程式運行耗時:0.11
總共處理了 109 張圖片


Python常見檔案操作樣本

os.path 模組中的路徑名訪問函數
分隔
basename() 去掉目錄路徑, 返迴文件名
dirname() 去掉檔案名稱, 返回目錄路徑
join() 將分離的各部分組合成一個路徑名
split() 返回 (dirname(), basename()) 元組
splitdrive() 返回 (drivename, pathname) 元組
splitext() 返回 (filename, extension) 元組

資訊
getatime() 返回最近訪問時間
getctime() 返迴文件建立時間
getmtime() 返回最近檔案修改時間
getsize() 返迴文件大小(以位元組為單位)

查詢
exists() 指定路徑(檔案或目錄)是否存在
isabs() 指定路徑是否為絕對路徑
isdir() 指定路徑是否存在且為一個目錄
isfile() 指定路徑是否存在且為一個檔案
islink() 指定路徑是否存在且為一個符號連結
ismount() 指定路徑是否存在且為一個掛載點
samefile() 兩個路徑名是否指向同個檔案

os.path.isdir(name):判斷name是不是一個目錄,name不是目錄就返回false
os.path.isfile(name):判斷name是不是一個檔案,不存在name也返回false
os.path.exists(name):判斷是否存在檔案或目錄name
os.path.getsize(name):獲得檔案大小,如果name是目錄返回0L
os.path.abspath(name):獲得絕對路徑
os.path.normpath(path):規範path字串形式
os.path.split(name):分割檔案名稱與目錄(事實上,如果你完全使用目錄,它也會將最後一個目錄作為檔案名稱而分離,同時它不會判斷檔案或目錄是否存在)
os.path.splitext():分離檔案名稱與副檔名
os.path.join(path,name):串連目錄與檔案名稱或目錄
os.path.basename(path):返迴文件名
os.path.dirname(path):返迴文件路徑


os模組中的檔案操作:
os 模組屬性
linesep 用於在檔案中分隔行的字串
sep 用來分隔檔案路徑名的字串
pathsep 用於分隔檔案路徑的字串
curdir 當前工作目錄的字串名稱
pardir (當前工作目錄的)父目錄字元串名稱

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

2.刪除:os.remove(file)
3.列出目錄下的檔案:os.listdir(path)
4.擷取當前工作目錄:os.getcwd()
5.改變工作目錄:os.chdir(newdir)
6.建立多級目錄:os.makedirs(r"c:\python\test")
7.建立單個目錄:os.mkdir("test")
8.刪除多個目錄:os.removedirs(r"c:\python") #刪除所給路徑最後一個目錄下所有空目錄。
9.刪除單個目錄:os.rmdir("test")
10.擷取檔案屬性:os.stat(file)
11.修改檔案許可權與時間戳記:os.chmod(file)
12.執行作業系統命令:os.system("dir")
13.啟動新進程:os.exec(), os.execvp()
14.在後台執行程式:osspawnv()
15.終止當前進程:os.exit(), os._exit()
16.分離檔案名稱:os.path.split(r"c:\python\hello.py") --> ("c:\\python", "hello.py")
17.分離副檔名:os.path.splitext(r"c:\python\hello.py") --> ("c:\\python\\hello", ".py")
18.擷取路徑名:os.path.dirname(r"c:\python\hello.py") --> "c:\\python"
19.擷取檔案名稱:os.path.basename(r"r:\python\hello.py") --> "hello.py"
20.判斷檔案是否存在:os.path.exists(r"c:\python\hello.py") --> True
21.判斷是否是絕對路徑:os.path.isabs(r".\python\") --> False
22.判斷是否是目錄:os.path.isdir(r"c:\python") --> True
23.判斷是否是檔案:os.path.isfile(r"c:\python\hello.py") --> True
24.判斷是否是連結檔案:os.path.islink(r"c:\python\hello.py") --> False
25.擷取檔案大小:os.path.getsize(filename)
26.*******:os.ismount("c:\\") --> True
27.搜尋目錄下的所有檔案:os.path.walk()

shutil模組對檔案的操作:
1.複製單個檔案:shultil.copy(oldfile, newfle)

2.複製整個分類樹:shultil.copytree(r".\setup", r".\backup")

3.刪除整個分類樹:shultil.rmtree(r".\backup")

臨時檔案的操作:
1.建立一個唯一的臨時檔案:tempfile.mktemp() --> filename

2.開啟臨時檔案:tempfile.TemporaryFile()

記憶體檔案(StringIO和cStringIO)操作
[4.StringIO] #cStringIO是StringIO模組的快速實現模組

1.建立記憶體檔案並寫入初始資料:f = StringIO.StringIO("Hello world!")
2.讀入記憶體檔案資料:print f.read() #或print f.getvalue() --> Hello world!
3.想記憶體檔案寫入資料:f.write("Good day!")
4.關閉記憶體檔案:f.close()

import osimport os.pathimport unittestimport time#import pygameclass PyFileCommonOperatorTest(unittest.TestCase):  def __init__(self):    """constructor"""    def test01(self):    print os.linesep    print os.sep    print os.pathsep    print os.curdir    print os.pardir    print os.getcwd()    print 'unittest here'if __name__ == "__main__":  t = PyFileCommonOperatorTest()  t.test01()

讀檔案的寫法

#讀檔案的寫法:#讀文字檔: input = open('data', 'r')#第二個參數是預設的,可以不加#讀二進位檔案: input = open('data', 'rb')#讀取所有檔案內容:open('xxoo.txt').read()#讀取固定位元組open('abinfile', 'rb').read(100)#讀每行file_object.readlines()


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.