如何从文本文件中捕获未注释的代码行?

时间:2015-05-30 03:53:48

标签: python

我有一个类似这样的文本文件:

#<[_MOUNTING] Recessed
#<[_FAMILY] RT8
#<[_PRODUCTID] cecf8545-0ff3-4d4a-bafd-dbb156bab282
#<[_BALLAST_TYPE] ELECTRONIC
#<[_FIXTURE_TYPE] 2X4 Volumetric
#<[_TERCAT] Recessed, Linear
#<[_TER] 72
# 54.8 watt luminaire, lamp*ballast factor = 1

void brightdata 2RT8S_2_32_LP735_dist
23 flatcorr C:/rm/ies/2RT8S_2_32_LP735.dat source.cal src_phi4 src_theta -i 1 -t 3.2 0.9 2.9 -i 0 -t 2.44 0.0 0.0 -i 0 -t -0.0 1.83 0.0
0
1            1.54935


# c:\daysim\bin\xform -n a0.1 -t 3.2 0.9 2.9 -i 0 -t 2.44 0.0 0.0 -i 1 -t -0.0 1.83 0.0
# c:\daysim\bin\ies2rad -dm -m 0.95 -t white -o C:/rm/ies/2RT8S_2_32_LP735
# Dimensions in meters
#<[_PRODUCTID] cecf8545-0ff3-4d4a-bafd-dbb156bab282
#<[_BALLAST_TYPE] ELECTRONIC
#<[_FIXTURE_TYPE] 2X4 Volumetric
#<[_TERCAT] Recessed, Linear
#<[_TER] 72
# 54.8 watt luminaire, lamp*ballast factor = 1

void brightdata 2RT8S_2_32_LP735_dist
23 flatcorr C:/rm/ies/2RT8S_2_32_LP735.dat source.cal src_phi4 src_theta -i 1 -t 3.2 0.9 2.9 -i 0 -t 2.44 0.0 0.0 -i 1 -t -0.0 1.83 0.0
0
1            1.54935

2RT8S_2_32_LP735_dist light 2RT8S_2_32_LP735_light
0
0
3                  1                  1                  1

# c:\daysim\bin\xform -n a0.2 -t 3.2 0.9 2.9 -i 0 -t 2.44 0.0 0.0 -i 2 -t -0.0 1.83 0.0
# c:\daysim\bin\ies2rad -dm -m 0.95 -t white -o C:/rm/ies/2RT8S_2_32_LP735
# Dimensions in meters
#<IESNA:LM-63-2002
#<[TEST] LTL18481
#<[TESTDATE] 1/28/2010

我想捕获未注释的代码行并将它们写入单独的文件中。对于缺乏一个更好的词,最多的&#39; pythonic&#39;这样做的方法?我已经使它成功了,但我不认为我的方式非常优雅。我的代码如下。

from __future__ import print_function
lumdict={}
counter = 1
b =False

with open(radFile) as rad:
    a=[] #Create a temp list to capture noncommented data.
    for lines in rad:

        if not lines.startswith("#"):
            a.append(lines) #Add non commented data to templist
        else:
            if len(a)>0: 
                lumdict[counter]=a #Capture non commented data into a dictionary.
                b=a[:] #This is the list meant to be used for the last bit of non commented data.
                a=[]
                counter +=1
    else:
        lumdict[counter]=b


for zones,radvalues in lumdict.items(): #Write the dictionary to individual files.
    with open(r'd:\zones\{}.rad'.format(zones),'w') as zonefile:
        for lines in radvalues:
            print(lines,file=zonefile,end="")

2 个答案:

答案 0 :(得分:1)

嗯,我知道你要求一个python工具。但作为替代方案,您可以选择使用shell命令来执行此操作:

grep -v '^#' foo.txt > bar.txt

答案 1 :(得分:1)

您可以在迭代时写入文件,而不是创建一个包含以下内容的字典:

from __future__ import print_function

with open(radFile) as rad:
    counter = 0
    zonefile = open(r'd:\zones\{}.rad'.format(counter),'w')
    for line in rad:
        if not line.startswith("#"):
            if zonefile.closed:
                counter += 1
                zonefile = open(r'd:\zones\{}.rad'.format(counter),'w')
            print(line, file=zonefile)
        else:
            zonefile.close()
    zonefile.close()