国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python實現(xiàn)讀取目錄所有文件的文件名并保存到txt文件代碼

2020-02-23 06:13:47
字體:
供稿:網(wǎng)友

代碼: (使用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()

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 博白县| 庆云县| 凌海市| 台前县| 泌阳县| 北海市| 报价| 望城县| 巧家县| 河津市| 黎平县| 遂平县| 高平市| 曲水县| 拜泉县| 治县。| 延川县| 怀远县| 荆州市| 武平县| 临清市| 濉溪县| 洮南市| 交口县| 彩票| 房山区| 营山县| 金川县| 丹阳市| 且末县| 贺州市| 曲沃县| 景德镇市| 鸡泽县| 武穴市| 舞钢市| 永城市| 桂林市| 巴彦淖尔市| 阜新| 红原县|