Python實現(xiàn)讀取目錄所有文件的文件名并保存到txt文件代碼
代碼: (使用os.listdir)
import os
def ListFilesToTxt(dir,file,wildcard,recursion):
exts = wildcard.split(" ")
files = os.listdir(dir)
for name in files:
fullname=os.path.join(dir,name)
if(os.path.isdir(fullname) & recursion):
ListFilesToTxt(fullname,file,wildcard,recursion)
else:
for ext in exts:
if(name.endswith(ext)):
file.write(name + "\n")
break
def Test():
dir="J:\\1"
outfile="binaries.txt"
wildcard = ".txt .exe .dll .lib"
file = open(outfile,"w")
if not file:
print ("cannot open the file %s for writing" % outfile)
ListFilesToTxt(dir,file,wildcard, 1)
file.close()
Test()
代碼:(使用os.walk) walk遞歸地對目錄及子目錄處理,每次返回的三項分別為:當(dāng)前遞歸的目錄,當(dāng)前遞歸的目錄下的所有子目錄,當(dāng)前遞歸的目錄下的所有文件。
import os
def ListFilesToTxt(dir,file,wildcard,recursion):
exts = wildcard.split(" ")
for root, subdirs, files in os.walk(dir):
for name in files:
for ext in exts:
if(name.endswith(ext)):
file.write(name + "\n")
break
if(not recursion):
break
def Test():
dir="J:\\1"
outfile="binaries.txt"
wildcard = ".txt .exe .dll .lib"
file = open(outfile,"w")
if not file:
print ("cannot open the file %s for writing" % outfile)
ListFilesToTxt(dir,file,wildcard, 0)
file.close()
Test()
- Python讀寫txt文本文件的操作方法全解析
- python 如何將數(shù)據(jù)寫入本地txt文本文件的實現(xiàn)方法
- Python將列表數(shù)據(jù)寫入文件(txt, csv,excel)
- Python3將數(shù)據(jù)保存為txt文件的方法
- Python中使用不同編碼讀寫txt文件詳解
- python讀取txt文件并取其某一列數(shù)據(jù)的示例
- 對python .txt文件讀取及數(shù)據(jù)處理方法總結(jié)
- python 將print輸出的內(nèi)容保存到txt文件中
- python如何將兩個txt文件內(nèi)容合并
- 如何利用Python打開txt格式的文件
相關(guān)文章
Python 圖片文字識別的實現(xiàn)之PaddleOCR
OCR方向的工程師,之前一定聽說過PaddleOCR這個項目,其主要推薦的PP-OCR算法更是被國內(nèi)外企業(yè)開發(fā)者廣泛應(yīng)用,短短半年時間,累計Star數(shù)量已超過15k,頻頻登上Github Trending和Paperswithcode 日榜月榜第一2021-11-11python polars數(shù)據(jù)科學(xué)庫對比Pandas優(yōu)勢分析
這篇文章主要為大家介紹了python polars數(shù)據(jù)科學(xué)庫對比Pandas優(yōu)勢分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2024-01-01beam search及pytorch的實現(xiàn)方式
這篇文章主要介紹了beam search及pytorch的實現(xiàn)方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-05-05keras打印loss對權(quán)重的導(dǎo)數(shù)方式
這篇文章主要介紹了keras打印loss對權(quán)重的導(dǎo)數(shù)方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06Elasticsearches的集群搭建及數(shù)據(jù)分片過程詳解
這篇文章主要為大家介紹了Elasticsearches的集群搭建及數(shù)據(jù)分片過程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-04-04