python这样把一个目录下的文件名保存到txt,而且不要扩展名,

python这样把一个目录下的文件名保存到txt,而且不要扩展名,

用os模块的os.walk()和os.listdir()可以解决,具体用法可以去查手册

> python这样把一个目录下的文件名

这样?  文件名?  

请说清楚你要解决的问题, 另外你尝试了什么解决办法?

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()

用这个A代码可以实现指定文件目录下 指定文件格式的 文件名 输出到 binaries.txt,但是文件带后缀名。 不知道这么去掉。 

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)):
                    (filename,extension) = os.path.splitext(name)
                    file.write(filename + " \n")
                    break
def Test():
  dir=r'E:\2021\桌面'
  outfile="depth.txt"
  wildcard = ".png .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()

这个代码可以解决我提出的问题,但是想要解决问题还没有完成。 现在需要加上

文件名的全部路径放在文件名右边,应该这么写代码,