1. linux裡面import os作用是什麼
import os
print(os.path.abspath(".")) #當前目錄的絕對路徑
print(os.path.abspath(r"..")) #上級目錄的絕對路徑 print(os.path.abspath(r"D:\python_workshop\python6\revise\函數.py"))
運行結果
D:\python_workshop\python6\selenium_webdriver
D:\python_workshop\python6
D:\python_workshop\python6\revise\函數.py
其他的一些常見函數:
1、os.getcwd()函數
功能:獲取當前目錄,python 的工作目
import os
pwd = os.getcwd()
print (pwd)
2、os.name 函數
功能:獲取當前使用的操作系統(獲取信息不夠詳細)
其中 'nt' 是 windows,'posix' 是 linux 或者 unix
import os
name = os.name
if name == 'posix':
print ("this is Linux or Unix")
elif name == 'nt':
print ("this is windows")
else:
print ("this is other system")
3、os.remove()函數
功能:刪除指定文件
eg:刪除 file.txt 文件
import os
os.remove(』file.txt『)
4、os.removedirs()函數
功能:刪除指定目錄
eg:刪除 file目錄
import os
os.removedirs(『file』)
5、os.system()函數
功能:運行shell命令
eg:執行ls -a > 1.txt命令
import os
os.system(『ls -a > 1.txt』)
6、os.mkdir()函數
功能:創建一個新目錄
eg:創建一個 file 目錄
import os
os.mkdir(『file』)
7、os.chdir()函數
功能:改變當前路徑到指定路徑
eg:我現在從當前路徑到 filepath 所指定的路徑下
import os
filepath = '/home'
pwd = os.getcwd()
print (pwd)
os.chdir(filepath)
pwd = os.getcwd()
print (pwd)
8、os.listdir()函數
功能:返回指定目錄下的所有目錄和文件
eg:列出當前目錄下的所有文件和目錄
import os
pwd = os.getcwd()
name = os.listdir(pwd)
for filename in name:
print (filename)