python之os庫


python之os庫

os.name 判斷現在正在實用的平台,Windows 返回 ‘nt‘; Linux 返回’posix‘

>>> os.name
'nt'

os.getcwd() 得到當前工作的目錄。

>>> os.getcwd()
'D:\\Program Files\\Sublime Text 3'

os.listdir() 指定所有目錄下所有的文件和目錄名。例:

>>> os.listdir()
['5ae74167-5539-4ef6-93c6-dd0cf223b5ce.dmp', 'changelog.txt', 'crash_reporter.exe', 'msvcr100.dll', 'Packages', 'plugin_host.exe', 'python3.3.zip', 'python33.dll', 'subl.exe', 'sublime.py', 'sublime_plugin.py', 'sublime_text.exe', 'unins000.dat', 'unins000.exe', 'unins000.msg', 'update_installer.exe']

以列表的形式全部列舉出來,其中沒有區分目錄和文件。

os.mkdir() 創建目錄

>>> os.mkdir('新建文件夾')
>>>> os.listdir()
['5ae74167-5539-4ef6-93c6-dd0cf223b5ce.dmp', 'changelog.txt', 'crash_reporter.exe', 'msvcr100.dll', 'Packages', 'plugin_host.exe', 'python3.3.zip', 'python33.dll', 'subl.exe', 'sublime.py', 'sublime_plugin.py', 'sublime_text.exe', 'unins000.dat', 'unins000.exe', 'unins000.msg', 'update_installer.exe', '新建文件夾']

注意:這樣只能建立一層,要想遞歸建立可用:os.makedirs()
os.rmdir() 刪除指定目錄

>>> os.listdir()
['5ae74167-5539-4ef6-93c6-dd0cf223b5ce.dmp', 'changelog.txt', 'crash_reporter.exe', 'msvcr100.dll', 'Packages', 'plugin_host.exe', 'python3.3.zip', 'python33.dll', 'subl.exe', 'sublime.py', 'sublime_plugin.py', 'sublime_text.exe', 'unins000.dat', 'unins000.exe', 'unins000.msg', 'update_installer.exe']

os.remove() 刪除指定文件


os.path.isfile() 判斷指定對象是否為文件。是返回True,否則False

>>> os.path.isfile('sublime.py')
True

os.path.isdir() 判斷指定對象是否為目錄。是True,否則False。例:

>>> os.path.isdir('sublime.py')
False

os.path.exists() 檢驗指定的對象是否存在。是True,否則False.例:

>>> os.path.exists('新建文件夾')
False

os.path.split() 返回路徑的目錄和文件名。例:

>>> temp = os.path.split(os.getcwd())
>>> type(temp)
<class 'tuple'>
>>> temp[0]
'D:\\Program Files'
>>> temp[1]
'Sublime Text 3'

此處只是把前后兩部分分開而已。就是找最后一個‘/‘。

os.system() 執行shell命令。

>>> os.system("echo 'hello world'")
'hello world'
0

os.chdir() 改變目錄到指定目錄

>>> os.chdir(temp[0])
>>> os.getcwd()
'D:\\Program Files'

os.path.join(path, name) 連接目錄和文件名。例:

>>> os.path.join(temp[0],temp[1])
'D:\\Program Files\\Sublime Text 3'

os.path.getsize() 獲得文件的大小,如果為目錄,返回0

>>> os.path.getsize('D:\\Program Files\\Sublime Text 3')
4096

os.path.basename(path) 返回文件名

>>> os.path.basename('D:\\Program Files\\Sublime Text 3')
'Sublime Text 3'

os.path.abspath() 獲得絕對路徑。

os.path.dirname(path) 返回文件路徑


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM