Hi. I am a beginner with Python. I've done some PHP work in the past but I suspect this is not helping with my progress in Python.
I have a text file that basically looks like this:
a=1
b=2
c=3
a=4
b=5
c=6
a=7
c=8
a=9
b=0
c=11
At the end of the day I would like to have a file that looks like this:
A, B, C
1, 2, 3
4, 5, 6
7, , 8
9, 0, 11
I was asked to do something similar at work last week and while I did manage to get the data into a CSV file(because everybody loves Excel here where I work) I'm not sure the way I went about it was the best:
#!/usr/local/bin/python2.6
import re
fileout_ = open('output.txt', 'w')
listsml_ = {}
listbig_ = []
with open('input.txt', 'r') as thefile_:
for line_ in thefile_:
match_a = re.compile(r'^a=(.*?)$').search(line_)
if match_a != None:
listsml_['a'] = match_a.group(1)
match_b = re.compile(r'^b=(.*?)$').search(line_)
if match_b != None:
listsml_['b'] = match_b.group(1)
match_c = re.compile(r'^c=(.*?)$').search(line_)
if match_c != None:
listsml_['c'] = match_c.group(1)
listbig_.append(listsml_)
listsml_ = {}
fileout_.write("A, B, C\n")
for line in listbig_:
if line.has_key('a'):
A = line['a']
else:
A = ""
if line.has_key('b'):
B = line['b']
else:
B = ""
if line.has_key('c'):
C = line['c']
else:
C = ""
lineout_ = "%s, %s, %s\n" % (A, B, C)
fileout_.write(lineout_)
fileout_.close()
I can see a few things that troubles me. For instance "listbig_.append(listsml_)" will only work when the loop gets to a line that contains '^c=(.*?)$'. But this won't work if the data only contains a=whatever and b=whatever.
Also, this is my scripting way of doing things. Do step a then step b then... I'm sure there must be an object oriented approach to this task but I do not know where to begin. At this stage I'm just frustrated as I don't know where to go from here. I'll have more of these sorts of projects to do in the future and I'm not sure what the next step would be. Any help appreciated. Thanks