countTxt(dirPath):
参数 dirPath 是一个文件夹的路径,该函数的功能是统计该文件夹中 txt 文件的数量(不考虑子文件夹中的文件),函数返回值类型为整数型,如输入为'step1/case1'时,返回值为 7。
这个函数怎么写
在 Python 中,splitext 函数用于分离文件名与扩展名
import os
def countTxt(dirPath):
# 参数 dirPath 是一个文件夹的路径,该函数的功能是统计该文件夹中 txt 文件的数量(不考虑子文件夹中的文件),
# 函数返回值类型为整数型,如输入为'step1/case1'时,返回值为 7。
count=0
for path in os.listdir(dirPath):
if os.path.splitext(path)[-1]==".txt":
count+=1
return count
if __name__=="__main__":
cwd=os.getcwd()
num=countTxt(cwd)
print("{}目录下有{}个txt文件".format(cwd,num))
import os
dirPath = ''
def countTxt(dirPath):
count = 0
for i in os.listdir(dirPath):
if i[-3:] == 'txt':
count += 1
return count
import os
def countTxt(dirPath):
count = 0
for path in os.listdir(dirPath):
if path.split('.')[-1] == 'txt':
count += 1
return count
if __name__ == '__main__':
# 文件夹路径
dirPath = './'
count = countTxt(dirPath)
print('该目录下有%d个txt文件' % count)