我有一個是這樣的一個文本文件:如何從文本文件中捕獲非註釋的代碼行?
#<[_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
我想捕捉的代碼不註釋行,並將其寫入到單獨的文件。缺乏一個更好的詞,會是什麼呢,這是最「pythonic」的方式來做到這一點?我已經做到了,但是我不認爲我的方式非常優雅。我的代碼如下。
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="")
也許你可以澄清一點。從您的解決方案看來,您希望將註釋之間的每個未註釋行塊都捕獲到其自己的文件中,而不是將每個未註釋行記錄到單獨的文件中。它是否正確? –
'b'的用途還不完全清楚。最初它是一個布爾值(False),但它成爲一個列表。另外,'for-else'分支的確切目的是什麼? – dlask
@EricAppelt是的,完全如您所述。 –