I have a text file that has many occurrences of the following lines:
G=
rtc={22/06/30,18:32:30}
B=52,12,13,4,T=421,29,29,4
Ba=28.32,Bs=15.26,Br=1.38,1.96,2.00,3.39
Ns=286,Nf=117,A=0,1,E=0
I would like to extract all lines starting with 'B=' and put them into a csv file with headers 'B1', 'B2', 'B3', 'B4', 'T1', 'T2', 'T3', 'T4' where each row of the csv file is taken from one such pattern in the text file. Here is what I want to have
B1 B2 B3 B4 T1 T2 T3 T4
52 12 13 4 421, 29, 29, 4
.
.
.
I was able to create such a csv file. However, there is a caveat in the original dataset; not all the 5-line blocks necessarily have 8 values at the said position; some values are missing (nan). I would like to modify my code such that if the number of present values are less than 8, then the code print a nan in the missing spot without raising the "IndexError: list index out of range" error message. All I know is that there should be some statements replacing pass statement if the condition is not true. I would appreciate your help.
def attrs_reader(file, attrs_columns):
csvReader = csv.reader(file)
list_of_lists = []
for line in csvReader:
if len(line) == len(attrs_columns):
list_of_lists.append([
re.sub('B=', '', line[0]), line[1], line[2], line[3],
re.sub('T=', '', line[4]), line[5], line[6], line[7]
])
else:
pass
data = []
for i, lst in enumerate(list_of_lists):
data.append(lst)
df_attrs = pd.DataFrame(data, columns=attrs_columns)
return df_attrs