I am using the following code to write two files from the original data.dat file. Everytime I run it, it appends to the output files the outcome again and again and the files becomes too large. I want to overwrite the files sss.txt and rrr.txt everytime I run so that I do not have extra information.
Can someone please help?
import pandas as pd
d = ‘/home/Example1’
l = os.listdir(d)
for i in l:
p = os.path.join(d, i)
if os.path.isfile(p) and i == ‘data.dat’:
with open(p, 'r') as f: for index, line in enumerate(f.readlines()): if index % 2 == 0: with open(os.path.join(d, 'sss.txt'), 'a') as s1: s1.write(line) elif index % 2 == 1: with open(os.path.join(d, 'rrr.txt'), 'a') as s2: s2.write(line) elif index % 2 == 2: with open(os.path.join(d, 'Safety_file.txt'), 'a') as s3: s3.write(line)