Python3 檔案系統,

來源:互聯網
上載者:User

Python3 檔案系統,

今天學了python3 的檔案系統,高大上啊~~~~

1、os模組和 os.path模組os模組中檔案目錄和函數的使用方法
函數 使用方法
getcwd() 返回當前工作目錄
chdir(path) 改變工作目錄
listdir(path='.') 列舉指定目錄中的檔案名稱(‘.’表示當前陌路‘..’表示上一級目錄)
mkdir(path) 建立單層目錄,如果目錄已存在則拋出異常
makedirs(path) 建立多層目錄,如果目錄已存在則拋出異常 注意:E:\\a\\c和E:\\a\\b不會衝突
remove(path) 刪除檔案
rmdir(path) 刪除單層目錄,如果該目錄非空則拋出異常
removedirs(path) 遞迴刪除目錄,從子目錄到父目錄逐層嘗試刪除,遇到目錄非空則拋出異常
rename(old,new) 將檔案old重新命名為new
system(commend) 運行系統的shell命令
walk(top) 遍曆top路徑以下所有的子目錄,返回一個三元組(路徑,[包含目錄],[包含檔案])
  以下是支援路徑操作中常用到的一些定義,支援所有平台
os.curdir 指代目前的目錄'.' 用os.curdir表示目前的目錄更準確(怡紅院來者不拒哈哈哈)
os.pardir 指代上一級目錄‘..’
os.sep 輸出作業系統特定的路徑分割符(WIN下為'\\'Linux下為'/')
os.linesep 當前作業系統下的行終止符(win下為'\r\n' Linux下為'\n')
os.name 指代當前的作業系統(‘posix’ ‘nt’ ‘mac’ ‘os2’ ‘ce’ ‘java’)打到這到這覺得Python好好用...

 

os.path模組中關於路徑常用的函數使用方法
函數名 使用方法
basename(path) 去掉目錄路徑單獨返迴文件名
dirname(path) 去掉檔案名稱單獨返回目錄路徑
join(path1[,path[,...]]) 將path1和path2各部分組合成一個路徑名
split(path)

分割檔案名稱與路徑,返回(f_path,f_name)形式的元組,如果都是目錄,他也會將最後一個目錄作為檔案分離

,且不會判斷檔案或者目錄是否存在

splitext(path) 分離檔案名稱和副檔名返回(f_name,f_ext)形式的元組

>>> import os
>>> os.path.splitext('boy_1.txt')
('boy_1', '.txt')

 getsize(file)  返回指定檔案尺寸,大小為位元組
 getatime(file)  返回指定檔案最近的訪問時間(浮點型秒數,可用time模組的gmtime()和localtime()轉換)
 getctime(file)  返回指定檔案的建立時間(浮點型秒數,可用time模組的gmtime()和localtime()轉換)
 getmtime(file)  返回指定檔案最新修改時間(浮點型秒數,可用time模組的gmtime()和localtime()轉換)
   以下函數返回True or False
 exists(path)  判定指定路徑(檔案或目錄)是否存在
 isabs(path)  判斷路徑是否為絕對路徑 絕對路徑:E:\\A\\B\\text.txt 相對路徑:A\\B\\text.tx
 isdir(path)  判斷路徑是否存在且一個目錄
 isfile(path)  判斷路徑是否存在且是一個檔案
 islink(path)  判斷路徑是否存在且是一個符號連結
 ismount(path)  判斷路徑是否存在且是一個掛載點 :E:\\ C:\\
 samefile(path1,path2)  判斷兩個路徑是否指向同一個檔案

 

 例題:1、統計目前的目錄下每個檔案類型個數(改進版)
import osc=os.getcwd()name_in_file=os.listdir(c)def count_filetype(name):    count=0    content=[]#用來儲存該路徑下所有副檔名        for each_name in name_in_file:        Suffix=os.path.splitext(each_name)        content.append(Suffix[1])    type_count=set(content)#集合裡的元素是唯一的,這樣就可以把相同的副檔名去掉得到檔案含有的副檔名    #print(type_count)           for Extension in type_count:        for Splited_Ext in content:            if Extension == Splited_Ext:                if Extension=='':                    Extension='檔案夾'                 count+=1        print('該檔案夾下共有類型為【%s】的檔案 %d 個'%(Extension,count))        count=0#統計完一次計數器清零    return 1count_filetype(name_in_file)

 2、輸入檔案名稱搜尋指定檔案夾是否存在該檔案
import osdef Find_Aim_File(path,file_name):    os.chdir(path)#1.改變工作路徑    container = os.walk(os.getcwd())#2.擷取當前工作路徑,3.遍曆該路徑下所有子目錄    for each in container:        for each_name in each[2]:            if each_name == file_name:                print(each[0]+os.sep+each_name)                                Initial_direct=input('請輸入尋找的初始目錄:')Target_File=input('請輸入需要尋找的目標檔案:')Find_Aim_File(Initial_direct,Target_File)

3、計算工作目錄下各個檔案的大小
import osc=os.getcwd()#返回當前工作目錄#使用os.curdir 表示目前的目錄更標準List_File_Nname=os.listdir(c)#列舉該目錄下的檔案名稱,返回一個列表def Get_File_Size(list_file_name):    for each_name in list_file_name:        print("%s【%d Bytes】"%(each_name,os.path.getsize(each_name)))        Get_File_Size(List_File_Nname)

4、尋找指定路徑的視頻檔案,並儲存路徑為文字文件(AV沒地方藏了doge臉)
import osdef Find_Vedio(directory,save_path):    flag=0    save_data=[]    os.chdir(directory)#改變工作目錄    container=os.walk((os.getcwd()))#擷取當前工作目錄#遍曆該目錄下所有子目錄       for sub_directory in container:        for each_file_name in sub_directory[2]:            splited_file_name=os.path.splitext(each_file_name)#返回[檔案名稱,副檔名]            if splited_file_name[1] in ['.avi','.mp4','.rmvb']:                #vedio_name=(sub_directory[0]+'\\'+each_file_name+'\n')                vedio_name=(sub_directory[0]+os.sep+each_file_name+os.linesep)#改成這句使程式更標準                save_data.append(vedio_name)                print(vedio_name)                flag=1    save_txt=open(save_path,'w')    print('儲存中.....')    save_txt.writelines(save_data)    save_txt.close()    print('主人我已為你打包完畢~~')         if flag==0:        print('真是不看片的好小夥!居然找不到!!!')        print('請輸入待尋找的初始目錄:',end='')while 1:    initial_directory = input()    print('請輸入儲存路徑(預設為【E:\\vedioList.txt】):',end='')    Savepath=input()    if Savepath=='':        Savepath='E:/vedioList.txt'    if ':\\' not in initial_directory and ':\\'not in Savepath:        print("格式錯誤請重新輸入:",end='')        continue    else:        print('尋找中....')        Find_Vedio(initial_directory,Savepath)        print('感謝使用')        break

 

 

 

5、尋找當前檔案夾內文字文件內是否含有關鍵字並輸出位置
import ospath=os.getcwd()container=os.walk(path)def find_txt(path):    txt_name_container=[]#存放文字檔檔案名稱        for each_path in container:#each_path的格式為(路徑,[包含目錄],[包含檔案])        for each_file_name in each_path[2]:            splited_name=os.path.splitext(each_file_name)#將檔案名稱和副檔名拆分返回一個列表            if splited_name[1]=='.txt':                #file_path=each_path[0]+'\\'+each_file_name#得到文字檔路徑                file_path=os.path.join(each_path[0],each_file_name)#上面這句話可以改成這一句                txt_name_container.append(file_path)#將文字檔路徑存入列表                return txt_name_containerdef find_keyword(target_file_list,key_word,c):    positions=[]    flag=0    for each_file_name in target_file_list:        row=0        txt_file=open(each_file_name)#以唯讀文本方式開啟檔案        for each_line in txt_file:            if key_word in each_line:                print('===================================================')                print('在檔案【%s】中找到關鍵字【%s】'%(each_file_name,key_word))                flag=1                txt_file.close()                break        if flag==0:            print("沒有在該檔案夾中找到關鍵字!")            break        elif flag==1 and c in ['YES','yes','y','Y']:             txt_file=open(each_file_name)            for each_line in txt_file:                end=len(each_line)                #print(end)                row+=1                for start in range(end):                    p=(each_line.find(key_word,start,end)+1)                    #print(p)                    if p!=0 and p not in positions:                        positions.append(p)                if positions :                                        print('關鍵字出現在第%d行第%s個位置'%(row,positions))                                positions=[]            txt_file.close()       

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.