導航:首頁 > 文件目錄 > python查找文件的內容

python查找文件的內容

發布時間:2024-03-24 15:02:59

『壹』 如何用Python os.path.walk方法遍歷搜索文件內容的操作詳解

本文是關於如何用Python os.path.walk方法遍歷搜索文件目錄內容的操作詳解的文章,python 代碼中用os.path.walk函數這個python模塊的方法來遍歷文件,python列出文件夾下的所有文件並找到自己想要的內容。
文中使用到了Python os模塊和Python sys模塊,這兩個模塊具體的使用方法請參考玩蛇網相關文章閱讀。
Python os.path.walk方法遍歷文件搜索內容方法代碼如下:
?

041
import os, sys#代碼中需要用到的方法模塊導入 listonly = False skipexts = ['.gif', '.exe', '.pyc', '.o', '.a','.dll','.lib','.pdb','.mdb'] # ignore binary files def visitfile(fname, searchKey): global fcount, vcount try: if not listonly: if os.path.splitext(fname)[1] in skipexts: pass elif open(fname).read().find(searchKey) != -1: print'%s has %s' % (fname, searchKey) fcount += 1 except: pass vcount += 1 #www.iplaypy.com def visitor(args, directoryName,filesInDirectory): for fname in filesInDirectory: fpath = os.path.join(directoryName, fname) if not os.path.isdir(fpath): visitfile(fpath,args) def searcher(startdir, searchkey): global fcount, vcount fcount = vcount = 0 os.path.walk(startdir, visitor, searchkey) if __name__ == '__main__': root=raw_input("type root directory:") key=raw_input("type key:") searcher(root,key) print 'Found in %d files, visited %d' % (fcount, vcount)

『貳』 用「python」怎麼提取文件里的指定內容

python讀取文件內容的方法:

一.最方便的方法是一次性讀取文件中的所有內容並放置到一個大字元串中:

all_the_text = open('thefile.txt').read( )
# 文本文件中的所有文本
all_the_data = open('abinfile','rb').read( )
# 二進制文件中的所有數據

為了安全起見,最好還是給打開的文件對象指定一個名字,這樣在完成操作之後可以迅速關閉文件,防止一些無用的文件對象佔用內存。舉個例子,對文本文件讀取:

file_object = open('thefile.txt')
try:
all_the_text = file_object.read( )
finally:
file_object.close( )

不一定要在這里用Try/finally語句,但是用了效果更好,因為它可以保證文件對象被關閉,即使在讀取中發生了嚴重錯誤。

二.最簡單、最快,也最具Python風格的方法是逐行讀取文本文件內容,並將讀取的數據放置到一個字元串列表中:list_of_all_the_lines = file_object.readlines( )

這樣讀出的每行文本末尾都帶有" "符號;如果你不想這樣,還有另一個替代的辦法,比如:
list_of_all_the_lines = file_object.read( ).splitlines( )
list_of_all_the_lines = file_object.read( ).split(' ')
list_of_all_the_lines = [L.rstrip(' ') for L in file_object]

『叄』 用python模糊檢索EXCEL文件的內容,並寫入新的EXCEL表

這類基礎邏輯編程初學可以手寫邏輯,這個基本如下:

  1. 載入基礎信息(Excel地址)

    ###手動指定###

  2. 獲取輸入查詢數據

    ###input()獲取,保存指變數###

  3. 打開Excel文件

    ####使用openpyxl打開,獲取工作簿對象和表對象####

  4. 獲取excel有效行與列數據

    ### 可以函數判斷,最好手工寫非空判斷獲取####

  5. 遍歷返回結果數據

    ### 讀取每個單元格 查詢字元串即可,習慣用Count還是find函數看具體需求和習慣###

  6. 寫入文件

    同樣可以採用openpyxl寫入excel或者直接寫入txt文件

『肆』 python如何查看文件內容

open('文件名').read()

閱讀全文

與python查找文件的內容相關的資料

熱點內容
dji悟固件升級 瀏覽:705
什麼網站能看所有的走秀視頻 瀏覽:781
外國四個字電影 瀏覽:354
win10優化文件夾有什麼用 瀏覽:422
微信分享回調地址 瀏覽:454
如何壓縮文件成幾個 瀏覽:642
樓上有人 韓國片 瀏覽:122
不卡頓電影網站 瀏覽:271
鎮江邁拓網路技術 瀏覽:985
怎樣找到路徑的文件 瀏覽:901
蘋果手機模特 瀏覽:997
男小三上位的小說 瀏覽:386
外國電影藍色皮膚的人 瀏覽:962
葛天中幾個老婆 瀏覽:260
網通合擊版本 瀏覽:76
ps分層文件加水印 瀏覽:104
生活中的瑪麗日本演員是誰 瀏覽:107
網路管理員績效考核指標 瀏覽:434
如何創建資料庫sql 瀏覽:59
蘋果8最新消息新聞 瀏覽:222

友情鏈接