我們經常會與文件和目錄打交道,對於這些操作python提供了一個os模塊,裏面包含了很多操作文件和目錄的函數。想要知道有哪些方法,我們可以運行下面的語句,就可以在屏幕上輸出os模塊的所有信息:
import os
help(os)
如果你對linux基本操作了解的話,下面的一些os方法應該會很熟悉的,因爲基本和linux下的操作方法相同。下面舉幾個常用的:1.os.getcwd() 獲得當前路徑
講到路徑,順便講講路徑的幾種方法
import os
Base1 = os.path.dirname(__file__)
Base2 = os.path.abspath(__file__)
BASE_DIR1 = os.path.dirname(os.path.dirname(__file__))
BASE_DIR2 = os.path.dirname(os.path.abspath(__file__))
join_dir = os.path.join(BASE_DIR1,'templates')
join_dir2 = os.path.join(BASE_DIR1, '..')
print "__file__: ",__file__
print "os.path.dirname: ",Base1
print "os.path.abspath: ",Base2
print "double dirname: ",BASE_DIR1
print "dirname and abspath: ",BASE_DIR2
print "join_dir: ",join_dir
#__file__: /Users/admin/PycharmProjects/test/dirTest.py
#os.path.dirname: /Users/admin/PycharmProjects/test
#os.path.abspath: /Users/admin/PycharmProjects/test/dirTest.py
#double dirname: /Users/admin/PycharmProjects
#dirname and abspath: /Users/admin/PycharmProjects/test
#join_dir: /Users/admin/PycharmProjects/templates
2.os.listdir(path) 獲得目錄中的內容
3.os.mkdir(path) 創建目錄
4.os.rmdir(path) 刪除目錄
5.os.isdir(path) os.isfile(path) 判斷是否爲目錄或者文件
6.os.remove(path) 刪除文件
7.os.rename(old, new) 重命名文件或者目錄
8.os.name 輸出字符串指示正在使用的平臺。如果是window 則用'nt'表示,對於Linux/Unix用戶,它是'posix'
9.os.system() 運行shell命令
10.os.path.split() 返回一個路徑的目錄名和文件名
11.os.path.splitext() 分離文件名與擴展名
12.os.path.getsize(name) 獲得文件大小,如果name是目錄返回0L
13.os.getegid() 返回當前進程(process)所屬的有效group id 只有unix可用
14.os.geteuid() 返回當前進程所屬的用戶ID (Unix)
15.os.getgid() 返回當前進程所屬的真實組ID(real group id)
16.os.getlogin() 返回當前登陸用戶名
17.os.getpgrp() 返回當前進程組的ID(Unix)
18.os.getpid() 返回當前進程的PID,( Unix, Windows )
19.os.getppid() 返回當前進程父進程的ID(Unix)
20.os.getuid() 返回當前進程所屬用戶ID(Unix)