python模組學習 os模組

2022-07-04 02:18:11 字數 2446 閱讀 1257

一、os模組概述

python os模組包含普遍的作業系統功能。例如檔案的複製、建立、修改、刪除檔案及資料夾...

二、常用方法

1、os.listdir()   返回指定目錄下的所有檔案和目錄名。

2、os.remove()  刪除乙個檔案。

3、os.system()  執行shell命令。

4、os.path.split()   函式返回乙個路徑的目錄名和檔名

5、os.path.isfile()和os.path.isdir()   函式分別檢驗給出的路徑是乙個檔案還是目錄,返回值分別為ture或false

6、os.path.exists

()    函式用來檢驗給出的路徑是否存在,返回值分別為ture或false。

7、os.path.getsize(name)   獲得檔案大小,如果name是目錄返回0l

8、os.path.splitext(name)     分離檔名與副檔名

9、os.path.join(path,name)   連線目錄與檔名或目錄

10、os.path.basename(path)    返回檔名

11、os.path.dirname(path)     返回檔案路徑

12、os.walk(path)   

該函式返回乙個元組,該元組有3個元素,這3個元素分別表示每次遍歷的路徑名,目錄列表和檔案列表

os.walk()舉例:>>> import os 

>>> for root, dirs, files in os.walk("

wd/chat

", topdown=false):

... for name in files:

... print(os.path.join(root, name)) #

列印檔案絕對路徑

... for name in dirs:

... print(os.path.join(root, name)) #列印目錄絕對路徑 ...

例項1:用python批量修改檔案的副檔名:

importos#

列出當前目錄下所有的檔案

files = os.listdir("."

)

for filename in

files:

portion =os.path.splitext(filename)

#如果字尾是.txt

if portion[1] == "

.pdb

":

#重新組合檔名和字尾名

newname = portion[0] + "

.dssp

"os.rename(filename,newname)

例項2:找出兩個資料夾中檔名不同的檔案(兩個資料夾中的副檔名是不同的)

#

-*- coding: utf-8 -*-

"""created on sun jul 12 10:55:03 2015

@author: chaofn

"""import

osfiles_ss=os.listdir('

g:/manesh_ss')

#生成manesh_ss目錄下去除副檔名的檔名列表

files1=[os.path.splitext(filename)[0] for filename in

files_ss]

files_ss2=os.listdir('

g:/manesh_ss2')

#生成manesh_ss2目錄下去除副檔名的檔名列表

files2=[os.path.splitext(filename)[0] for filename in

files_ss2]

for filename in

files1:

if filename not

infiles2:

print (filename)

例項3:更改目錄下所有檔案的字尾名

#

-*- coding: utf-8 -*-

"""created on sun jul 12 16:13:01 2015

@author: administrator

"""import

osfiles=os.listdir('

g:/manesh_ss')

for filename in

files:

newname=os.path.splitext(filename)[0]+'

.txt

'os.rename(

'g:/manesh_ss/%s

'%filename,'

g:/manesh_ss/%s

'%newname)

Python 模組學習 os模組

一 os模組概述 python os模組包含普遍的作業系統功能。如果你希望你的程式能夠與平台無關的話,這個模組是尤為重要的。一語中的 二 常用方法 1 os.name 輸出字串指示正在使用的平台。如果是window 則用 nt 表示,對於linux unix使用者,它是 posix 2 os.get...

Python 模組學習 os模組

一 os模組概述 python os模組包含普遍的作業系統功能。如果你希望你的程式能夠與平台無關的話,這個模組是尤為重要的。一語中的 二 常用方法 1 os.name 輸出字串指示正在使用的平台。如果是window 則用 nt 表示,對於linux unix使用者,它是 posix 2 os.get...

Python 模組學習 os模組

os模組提供了多個訪問作業系統服務的功能 os.name 顯示當前使用平台 os.getcwd 顯示當前python指令碼工作路徑 os.listdir dirname 顯示目錄dirname下的所有檔案和目錄名 os.remove filename 刪除乙個檔案 os.makedirs dirna...