需要在python中找到扩展名为.crv的文件中的字符串

时间:2017-09-21 13:37:41

标签: python-2.7

我有一项任务是从目录中获取所有文件,如果文件包含任何扩展名为.crv的文件,则读取文件。我已经使用Python编写了以下代码,但代码运行有问题。有些人可以帮助我找出可能出错的地方。

for file in os.listdir(location):
try:
    if file.endswith(".cxx"):
        #print "crvfile found:\t", file
        filepath = location+"\\"+file
        #print filepath
        cxxopenfile = open(filepath,"r")                
        for line in crvopenfile:
            line = line.rstrip()
            find = re.findall('^\S*(['.crv']+), line)
            #if len(find) > 0:
v
v
        cxxopenfile.close()
        cxxfiles.append(str(file))
        counter = counter+1   
except Exception as e:
    raise e
    print "No files found here!"

打印“找到的总文件数:\ t”,计数器

1 个答案:

答案 0 :(得分:0)

#!/usr/bin/env python
import os
import sys
import re
from os import listdir

location = "c:\\git\\repos\\test-code"
counter = 0
for file in os.listdir(location):
    try:
        if file.endswith(".cxx"):
            #print "crvfile found:\t", file
            filepath = location+"\\"+file
            #print filepath
            cxxopenfile = open(filepath,"r")                
            for line in cxxopenfile:
                line = line.rstrip()
                find = re.findall("^\S*['.crv']+", line)
                if len(find) > 0:
                    #cxxfiles.append(str(file))
                    counter = counter+1
                else:
                    print "No extension .crv found!"    
            cxxopenfile.close()            
    except Exception as e:
        raise e
        print "No files found here!"
print "Total files found:\t", counter

结果:

$ python ./test.py
No extension .crv found!
No extension .crv found!
No extension .crv found!
Total files found:      2