I wrote a code to produce the following output. It works fine when I use append function in marked line in code but when i use ''w' write function it, it only prints one line in the new created text file. Problem to use append function is if we run the code again it copies same output twice. I am not able to understand this . Please Help Thanks in advance
Code I used:
import os
with open("input5.csv", 'r+') as fd:
lines = fd.readlines()
fd.seek(0)
fd.writelines(line for line in lines if line.strip())
fd.truncate()
lines = open('input5.csv').readlines()
open('output1.txt', 'w').writelines(lines[1:-2])
with open('output1.txt', 'r+') as m:
newText = m.read()
while ',' in newText:
newText = newText.replace(',', '_')
with open('output1.txt', "w") as m:
m.write(newText)
with open("output1.txt","r+") as fp:
for cnt, line in enumerate(fp):
line=line.replace('_',',',3)
print(line)
f = open('output7.txt', 'a') #THIS LINE
for i in range(len(line)):
f.write((line[i]))
f.close()
os.remove("output1.txt")
Input:
id,name,amount,subject
1,abc,55,"s1,s2,s3"
1,abc1,56,"s4,s5,s6"
1,abc2,57,"s7,s8,s9"
1,abc3,58,"s10,s11,s12"
1,abc4,59,"s13,s14,s15"
1,abc5,59,"s16,s17,s18"
1,abc6,59,"s13,s14,s15"
1,abc7,59,"s13,s14,s15"
1,abc8,59,"s13,s14,s15"
1,abc9,59,"s13,s14,s15"
this file is done
time taken; 22nd
expected output:(This is the code i get when use append function marked line of the code)
1,abc,55,"s1_s2_s3"
1,abc1,56,"s4_s5_s6"
1,abc2,57,"s7_s8_s9"
1,abc3,58,"s10_s11_s12"
1,abc4,59,"s13_s14_s15"
1,abc5,59,"s16_s17_s18"
1,abc6,59,"s13_s14_s15"
1,abc7,59,"s13_s14_s15"
1,abc8,59,"s13_s14_s15"
1,abc9,59,"s13_s14_s15"
Output i get when I replace append with write function in marked line of code:
1,abc9,59,"s13_s14_s15"