I am trying to loop through every line in a text file and perform some actions. Right now I have a text file which contains this:
--- small modified --- #line 1
1,2,3 #line 2
4,5,6 #line 3
--- big modified --- #line 4
7;8;9 #line 5
10;11;12 #line 6
I am trying to parse line 2,3 into one file, and lines 5,6 into another file but right now, only lines 2 and 3 gets written into the file and idk why the "elif" statement is not run. I can't solve the logic error and would appreciate if someone could help me out.
Below is my code:
def convert_json(fileName):
with open(fileName,'r') as file:
for line in file:
if 'modified' and 'small' in line:
for li in file:
fields1 = li.split(',')
if len(fields1) >= 3:
smallarr.append({
"a": fields1[0],
"b": fields1[1],
"c": fields1[2]
})
with open('smalljson.txt','w+') as small_file:
json.dump(smallarr, small_file)
else:
pass
elif 'modified' and 'big' in line:
for li in file:
fields2 = li.split(';')
if len(fields2) >= 3:
bigarr.append({
"w1": fields2[0],
"w2": fields2[1],
"w3": fields2[2],
})
with open('big.txt','w+') as big_file:
json.dump(bigarr, big_file)
else:
pass
else:
print 'test'
Update: THis is my current code, I am able to do it but only for lines 2 and lines 5, other than s second for-loop i cannot think of another way to loop through the lines
def convert_json(fileName):
with open(fileName,'r') as file:
for line in file:
#if 'modified' in line and 'small' in line:
if 'modified' in line and 'Small' in line:
fields1 = next(file).split(',')
if len(fields1) >= 3:
smallarr.append({
"a": fields1[0],
"b": fields1[1],
"c": fields1[2]
})
with open('smalljson.txt','w+') as small_file:
json.dump(smallarr, small_file)
else:
pass
elif 'modified' in line and 'big' in line:
fields2 = next(file).split(';')
if len(fields2) >= 3:
bigarr.append({
"w1": fields2[0],
"w2": fields2[1],
"w3": fields2[2],
})
with open('bigwater.txt','w+') as big_file:
json.dump(bigarr, big_file)
else:
pass
else:
print 'test'
breakout. But you should be doing this with exactly 1 for-loop.