14.文件系统:高大上的东西——import关键字/模块
生活随笔
收集整理的這篇文章主要介紹了
14.文件系统:高大上的东西——import关键字/模块
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
模塊是一個(gè)包含所有定義的函數(shù)和變量的文件,其后綴
名是.py。模塊可以被別的程序引入,以使用該模塊中的
函數(shù)等功能。
import random
secret = random.randint(0,100)
OS模塊
http://bbs.fishc.com/forum.php?mod=viewthread&tid=45512&extra=page%3D1%26filter%3Dtypeid%26typeid%3D403
OS模塊中關(guān)于文件/目錄常用的函數(shù)
import os os.getcwd() #當(dāng)前工作目錄 os.chdir('C:\\') #改變當(dāng)前的工作目錄 os.listdir('C:\\') #查看C:\\目錄下的內(nèi)容os.mkdir('目錄名') #創(chuàng)建單層目錄 os.mkdirs('目錄名') #遞歸創(chuàng)建多層目錄os.remove('文件') #刪除文件 os.rmdir('目錄名') #刪除空目錄 os.rmdirs('目錄名') #遞歸刪除多個(gè)目錄os.rename(old,new) #將文件重命名system(command) #運(yùn)行系統(tǒng)的shell命令 例: >>> os.system('calc') >>> os.system('cmd')常量定義: os.curdir #當(dāng)前目錄 ./ os.pardir #上層目錄 ../os.sep #輸出操作系統(tǒng)特定的路徑分隔符(Win下為\\,linux下為/) os.linesep #當(dāng)前平臺(tái)使用的終止符(Win下為\r\n,linx下為\n) os.name #指代當(dāng)前使用的操作系統(tǒng)(包括:posix,nt,mac,os2,ce,java)os.path模塊中關(guān)于路徑常用的函數(shù)的使用方法
1. basename(path) #去掉目錄路徑,單獨(dú)返回文件名 dirname(path) #去掉文件名,單獨(dú)返回目錄路徑 >>> import os >>> os.path.basename('G:\\FishC.txt') 'FishC.txt'2. join(path1,path2,...) #將path1,path2,...等各部分組合成一個(gè)路徑名 >>> os.path.join('C','A','B','C') 'C\\A\\B\\C' >>> os.path.join('C:','A','B','C') 'C:A\\B\\C' >>> os.path.join('C:\\','A','B','C') #注意 'C:\\A\\B\\C'3.split(path):分割文件名與路徑,返回(f_path,f_name)元組。如果完全是目錄, 它也會(huì)將最后一個(gè)目錄作為文件名分離,且不會(huì)判斷文件或目錄是否存在。 >>> os.path.split('G:\\FishC.txt') ('G:\\', 'FishC.txt') >>> os.path.split('G:\\VOC2007\\Annotations\\') ('G:\\VOC2007\\Annotations', '') >>> os.path.split('G:\\VOC2007\\Annotations') ('G:\\VOC2007', 'Annotations')4.splitext(path):分離文件名和擴(kuò)展名,返回(f_name.f_extension)元組. >>> os.path.splitext('G:\\VOC2007\\Annotations\\000001.xml') ('G:\\VOC2007\\Annotations\\000001', '.xml')5.getsize(file):返回指定文件的尺寸(單位是字節(jié))。 >>> a = os.path.getsize('G:\\VOC2007\\Annotations\\000001.xml') >>> a 6861L 6.getatime(file):返回指定文件最新的訪問(wèn)時(shí)間(浮點(diǎn)數(shù)秒數(shù),可用 time模塊的gmtime()或者localtime()函數(shù)換算) 7.getctime(file):返回指定文件的創(chuàng)建時(shí)間 >>> a = os.path.getctime('G:\\VOC2007\\Annotations\\000001.xml') >>> a 1500992959.2363515 >>> import time >>> time.gmtime(a) time.struct_time(tm_year=2017, tm_mon=7, tm_mday=25, tm_hour=14, tm_min=29, tm_sec=19, tm_wday=1, tm_yday=206, tm_isdst=0) >>> time.localtime(a) time.struct_time(tm_year=2017, tm_mon=7, tm_mday=25, tm_hour=22, tm_min=29, tm_sec=19, tm_wday=1, tm_yday=206, tm_isdst=0) 8.getmtime(file):返回指定文件的最新修改時(shí)間以下OS模塊中的函數(shù)返回True或False
9.exists(path):判斷指定路徑(目錄或文件)是否存在 10.isabs(path):判斷指定路徑是否為絕對(duì)路徑 11.isdir(path):判斷指定路徑是否存在且是一個(gè)目錄 12.isfile(path):判斷指定路徑是否存在且是一個(gè)文件 13.islink(path):判斷指定路徑是否存在且是一個(gè)符號(hào)鏈接 14.ismount(path):判斷指定路徑是否存在且是一個(gè)掛載點(diǎn) 15.samefile(path1,path2):判斷path1和path2是否指向同一個(gè)文件總結(jié)
以上是生活随笔為你收集整理的14.文件系统:高大上的东西——import关键字/模块的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 13.文件:因为懂你,所以永恒
- 下一篇: 15.泡菜:pickle模块