python操作檔案

來源:互聯網
上載者:User

標籤:tool   mes   就會   names   ras   end   複製   xxxxx   pen   

讀寫

可以使用w,a,r,wb,ab,rb等模式

with open('xxx.xx', 'wb') as f:    f.write('xxxxxxxxx')

複製

如果destination是檔案夾,source檔案將複製到destination中,並保持原來的檔案名稱

如果destination是檔案名稱結尾,它將作為被複製檔案的新名字

shutil.copy(source, destination)

移動

如果destination是檔案夾,source 檔案將移動到destination中,並保持原來的檔案名稱

如果destination檔案夾中已存在source這個檔案,destination檔案夾中的同名檔案將被覆蓋

如果沒有destination檔案夾,就會將source改名為destination

shutil.move(source, destination)

刪除

os.unlink(file)刪除file檔案(單個檔案)

os.rmdir(path)刪除path檔案夾,該檔案夾必須為空白,其中沒有任何檔案和子檔案夾(單個空檔案夾)

shutil.rmtree(path)刪除path檔案夾,它包含的所有檔案和子檔案夾都會被刪除

send2trash.send2trash(file)將檔案夾和檔案發送到電腦的垃圾箱或資源回收筒,而不是永久刪除它們

os.walk()函數被傳入一個字串值,即一個檔案夾的路徑。你可以在一個 for

os.walk()遍曆分類樹,返回 3 個值:

1.當前遍曆的檔案夾名稱;

2.當前檔案夾中子資料夾清單;

3.當前檔案夾中檔案清單。

壓縮

# 建立壓縮檔以寫入模式開啟,寫入模式將擦除ZIP檔案中所有原有的內容

# 第二個參數傳入'a'則以添加模式開啟,將檔案添加到原有的 ZIP 檔案中,

>>> newZip = zipfile.ZipFile('new.zip', 'w')

# write()方法第一個參數傳入檔案,就會壓縮該檔案,將它加到ZIP檔案中,第二個參數是“壓縮類型”,告訴電腦使用怎樣的演算法來壓縮檔

>>> newZip.write('spam.txt', compress_type=zipfile.ZIP_DEFLATED)

>>> newZip.close()

開啟壓縮檔

>>> exampleZip = zipfile.ZipFile('example.zip')

# 查看壓縮檔中所有檔案和檔案夾的列表

>>> exampleZip.namelist()

['spam.txt', 'cats/', 'cats/catnames.txt', 'cats/zophie.jpg']

# 返回指定檔案的ZipInfo對象,ZipInfo對象有自己的屬性

>>> spamInfo = exampleZip.getinfo('spam.txt')

# 原來檔案大小

>>> spamInfo.file_size

13908

# 壓縮後檔案大小

>>> spamInfo.compress_size

3828

>>> 'Compressed file is %sx smaller!' % (round(spamInfo.file_size / spamInfo.compress_size, 2))

'Compressed file is 3.63x smaller!'

>>> exampleZip.close()

解壓

# extractall()從ZIP檔案中解壓所有檔案和檔案夾,放到當前工作目錄中

>>> exampleZip = zipfile.ZipFile('example.zip')

>>> exampleZip.extractall()

# 向extractall()傳遞檔案夾名稱,檔案將解壓到指定目錄

>>> exampleZip.extractall('C:\\ delicious')

>>> exampleZip.close()

# extract()從ZIP檔案中解壓單個檔案,第二個參數是解壓到指定目錄,如果指定檔案夾不存在,會自動建立

>>> exampleZip.extract('spam.txt')

'C:\\spam.txt'

>>> exampleZip.extract('spam.txt', 'C:\\some\\new\\folders')

'C:\\some\\new\\folders\\spam.txt'

>>> exampleZip.close()


python操作檔案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.