歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python文件或目錄操作的常用函數

Python文件或目錄操作的常用函數

日期:2017/3/1 9:52:50   编辑:Linux編程

Python文件或目錄操作的常用函數

◆ os.listdir(path)

Return a list containing the names of the entries in the directory given by path. The list is in arbitrary order. It does not include the special entries '.' and '..' even if they are present in the directory.

◆ os.getcwd() method displays the current working directory

◆ os.chdir() method to change the current directory

◆ other file and directory operation functions:

os.rename(current_file_name, new_file_name)

os.remove(file_name)

os.mkdir("newdir")

os.rmdir('dirname')

◆ 內置變量__file__可以獲得文件名(有可能是相對路徑名),進一步調用 os.path.realpath(__file__)可以獲得該文件的路徑完整路徑名(並且已經展開鏈接文件)。

◆ os.path.dirname(filename)可以獲得文件所在的目錄名。

◆ os.path.basename(filename)可以獲得完整路徑名最後的文件名,如果是一個目錄,則返回""。

◆ os.path.join(path1, path2)可以將多個路徑參數連接,這也是一個常用的函數。

◆ os.curdir和os.pardir是兩個常量字符串:"."和"..",分別表示當前目錄和上一級目錄的字符串。

◆ 獲取當前程序所在目錄的完整路徑

_curpath=os.path.normpath( os.path.join( os.getcwd(), os.path.dirname(__file__) ) )

推薦閱讀: Python學習總結—安裝與配置環境 http://www.linuxidc.com/Linux/2012-11/73912.htm

Copyright © Linux教程網 All Rights Reserved