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

2024-10-03 19:27:10 发布

您现在位置: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

我想捕获未注释的代码行,并将它们写入单独的文件中。如果没有一个更好的词,那么什么才是最“python”的方法呢?我已经成功了,但是我觉得我的方式不是很优雅。我的代码在下面。你知道吗

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="")

Tags: torminsrcfordatabintype
2条回答

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

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()

我知道你想要一个python实现。但也可以选择使用shell命令:

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

相关问题 更多 >