Python搜索目录,列出文件的基本名称,无扩展名

Python搜索目录,列出文件的基本名称,无扩展名,python,file,printing,directory,Python,File,Printing,Directory,我想知道是否有任何方法可以修改我的代码,只发布文件的基本名称,而不是包括扩展名在内的整个文件。。我是python新手,所以我知道的不多,我不想修改某些东西,让它完全崩溃 import glob import os os.chdir( "C:/headers" ) txt = open( 'C:/files.txt', 'w' ) for file in glob.glob( "*.h" ): with open( file ) as f: contents = f.r

我想知道是否有任何方法可以修改我的代码,只发布文件的基本名称,而不是包括扩展名在内的整个文件。。我是python新手,所以我知道的不多,我不想修改某些东西,让它完全崩溃

import glob
import os
os.chdir( "C:/headers" )

txt = open( 'C:/files.txt', 'w' )

for file in glob.glob( "*.h" ):
    with open( file ) as f:
        contents = f.read()
        if 'struct' in contents:
            txt.write( "%s\n"%file )
txt.close()
基本上,它所做的是搜索头文件目录,如果文件中有struct字符串,它将以txt文件的形式打印文件。但是,当我运行它时,会打开txt文件并列出所有文件,但我希望它只列出文件的基本名称,我不需要在它的末尾添加.h


请帮忙,谢谢

也许这会有帮助:

import glob
import os
import re
os.chdir( "C:/headers" )

txt = open( 'C:/files.txt', 'w' )

for file in glob.glob( "*.h" ):
    with open( file ) as f:
        contents = f.read()    [...]
        if 'struct' in contents:
            txt.write( "%s\n"% re.sub('\.h$', '', file) )
txt.close()

祝你好运

也许这会有帮助:

import glob
import os
import re
os.chdir( "C:/headers" )

txt = open( 'C:/files.txt', 'w' )

for file in glob.glob( "*.h" ):
    with open( file ) as f:
        contents = f.read()    [...]
        if 'struct' in contents:
            txt.write( "%s\n"% re.sub('\.h$', '', file) )
txt.close()
root, ext = os.path.splitext(file)
name = os.path.basename(root)
祝你好运

root, ext = os.path.splitext(file)
name = os.path.basename(root)
root
将包含给定文件名的整个路径,直到扩展名之前的句点,
name
将仅是不带前导路径的文件名


root
将包含给定文件名的整个路径,直到扩展名之前的句点,
name
将仅是没有前导路径的文件名。

仅在一行中…,返回找到的文件,不带任何文件扩展名,对于在给定搜索目录中找到的具有请求的文件扩展名的文件

Found_BaseFile_Names= [(f.split('.'))[0] for f in os.listdir(SearchDir) if f.endswith('.txt')]

只需在一行中…,返回在给定搜索目录中找到的文件(不带任何文件扩展名)以及请求的文件扩展名

Found_BaseFile_Names= [(f.split('.'))[0] for f in os.listdir(SearchDir) if f.endswith('.txt')]
@chakolatemilk——你有权删除评论(我不能告诉你我删除了多少不正确的评论)。只需点击光标在评论上移动时出现的灰色小“x”(光标在上面时会变成红色),它就会消失——除了版主之外,没有人能看到你的愚蠢错误:)@chakolatemilk——你有权删除评论(我无法告诉你我删除了多少不正确的评论)。只需单击鼠标移动到评论上时显示的灰色小“x”(当光标位于评论上时,它将变为红色),然后它就会消失--没有人(除了版主)能看到你的愚蠢错误:)