Python 搜索目录,列出文件基本名(无扩展名)
我在想有没有办法修改我的代码,让它只输出文件的基本名称,而不是整个文件名,包括后缀名。我刚学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。
请帮帮我,谢谢!
3 个回答
0
简单来说,这一行代码会返回在指定搜索目录中找到的文件,且这些文件没有任何扩展名,前提是这些文件是你请求的特定扩展名的文件!
Found_BaseFile_Names= [(f.split('.'))[0] for f in os.listdir(SearchDir) if f.endswith('.txt')]
3
root, ext = os.path.splitext(file)
name = os.path.basename(root)
root
会包含给定文件名的完整路径,直到扩展名之前的那个点的位置,而 name
只会是文件的名字,不包括前面的路径。
1
也许这会对你有帮助:
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()
祝你好运!